I want to pass a value from an Activity to a Fragment but my Activity doesn't have a layout.
I have used a barcode scanner so I want to send scanned data to Fragment class but I am getting a null value error, so please help me out.
public class ScanCasepaperActivity extends AppCompatActivity implements ZBarScannerView.ResultHandler,DiagnosisFragment.OnFragmentInteractionListener {
private ZBarScannerView mScannerView;
private String TAG = ScanCasepaperActivity.class.getName();
private static ScanCasepaperActivity context;
private TextView mCasePaperNo, mDateTime, mpatientName, mgender, mage, mrefBy;
private int CASEPAPERID;
DiagnosisFragment diagnosisFragment;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
// Programmatically initialize the scanner view
mScannerView = new ZBarScannerView(this);
setContentView(mScannerView);
//DiagnosisFragment DiagnosisFragment = new DiagnosisFragment(this);
}
#Override
public void onResume() {
super.onResume();
mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
mScannerView.startCamera(); // Start camera on resume
mScannerView.setAutoFocus(true);
}
#Override
public void onPause() {
super.onPause();
mScannerView.stopCamera(); // Stop camera on pause
}
#Override
public void handleResult(Result rawResult) {
Log.e(TAG, "handleResult");
DiagnosisFragment diagnosisFragment = new DiagnosisFragment();
Table_Barcode_Methods barcodeMethods = new Table_Barcode_Methods(getApplicationContext());
// Do something with the result here
long bar = Long.parseLong(rawResult.getContents());
int id = 0;
id = barcodeMethods.ISBarCodeNoAvailable(bar);
int s1 = 0;
s1 = (int) Long.parseLong(String.valueOf(id));
showFragment(s1);
//tableNewCasePaperMethods.getbar(s1);
// DiagnosisFragment.(s1);
// android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
// fragmentManager.beginTransaction().replace(R.id.content1, diagnosisFragment).commit();
// DiagnosisFragment.newInstance(args);
// diagnosisFragment = new DiagnosisFragment();
// DiagnosisFragment.newInstance(s1);
// Bundle bundle = new Bundle();
// bundle.putInt("id",s1);
// diagnosisFragment.setArguments(bundle);
// DiagnosisFragment.UpDateUI(s1);
Log.e(TAG + "barcodescanid", String.valueOf(id));
Log.e(TAG + "Contents", String.valueOf(bar)); // Prints scan results
Intent i1=new Intent(ScanCasepaperActivity.this,HomeActivity.class);
startActivity(i1);
}
}
if you want your activity shows in ScanCasepaperActivity,just add a method in your fragment and call it in your activity. if you wanna show a fragment in HomeActivity,pass your result through Intent or SharedPrefrece.
Related
I want implement next and previous buttons below the ExoPlayer. I'm basing my code on this thread:
Implementing next button in audio player android
and the links in these ones:
How to add Listener for next , previous , rewind and forward in Exoplayer
How to add next song and previous song play button in audio player using android studio2.3?
The Exoplayer is in a fragment and opens on the right side of the screen on a tablet screen and in a separate activity on a mobile screen when the user clicks on one of the recipe steps. Data to the StepsFragment(implements an onClickListener) is sent via parcelable from the parent activity(code below).
Next and previous buttons are only implemented on the mobile screen(code works fine). I'm passing the arraylist and position from the parent activity in the onClick method and retrieving them in the fragment. The code works fine w/o the buttons, and both the list and the position are sent via parcelable to the VideoFragment only to implement the buttons. I decided to put the buttons in the Video Fragment.
Nothing happens when clicking on either the next or previous button. Code flow is indicated in the comments above the code in the onClickListener. I've tried to debug but no errors are displayed. Is this the right way to pass the arraylist? Although it's not shown in the debug and the log cat, I think it might be null. Can someone please have a look? Thank you in advance.
VideoFragment(contains Exoplayer code):
public class VideoFragment extends Fragment
{
// Tag for logging
private static final String TAG = VideoFragment.class.getSimpleName();
/**
* Mandatory empty constructor for the fragment manager to instantiate the fragment
*/
public VideoFragment()
{
}
ArrayList<Steps> stepsArrayList;
Steps stepClicked;
Recipes recipes;
SimpleExoPlayer mExoPlayer;
#BindView(R.id.playerView)
SimpleExoPlayerView mPlayerView;
#BindView(R.id.thumbnail_url)
ImageView thumbnailUrlImage;
public int stepPosition;
private long mPlayerPosition;
String videoUrl;
Uri videoUrl_Parse;
Uri thumbnailUrl_Parse;
String thumbnailUrl;
#BindView(R.id.previous_button)
Button previousButton;
#BindView(R.id.next_button)
Button nextButton;
#BindView(R.id.step_long_description)
TextView stepLongDescription;
String stepLongDescriptionUrl;
boolean mTwoPane;
private static final String KEY_POSITION = "position";
public static final String STEPS_LIST_INDEX = "list_index";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
//Inflate the Steps fragment layout
View rootView = inflater.inflate(R.layout.fragment_video, container, false);
// Bind the views
ButterKnife.bind(this, rootView);
Bundle bundle = this.getArguments();
if (bundle != null)
{
//Track whether to display a two-pane or single-pane UI
stepClicked = getArguments().getParcelable("Steps");
if (stepClicked != null)
{
mTwoPane = getArguments().getBoolean("TwoPane");
stepPosition = getArguments().getInt("StepPosition");
stepsArrayList = getArguments().getParcelableArrayList("StepsArrayList");
stepsArrayList = new ArrayList<>();
videoUrl = stepClicked.getVideoUrl();
Log.i("VideoUrl: ", stepClicked.getVideoUrl());
videoUrl_Parse = Uri.parse(videoUrl);
thumbnailUrl = stepClicked.getThumbnailUrl();
thumbnailUrl_Parse = Uri.parse(thumbnailUrl);
stepLongDescriptionUrl = stepClicked.getStepLongDescription();
Log.i("Step: ", stepClicked.getStepLongDescription());
stepLongDescription.setText(stepLongDescriptionUrl);
if (thumbnailUrl != null)
{
Picasso.with(getContext())
.load(thumbnailUrl_Parse)
.into(thumbnailUrlImage);
}
}
if (mTwoPane)
{
previousButton.setVisibility(View.INVISIBLE);
nextButton.setVisibility(View.INVISIBLE);
} else
{
previousButton.setVisibility(View.VISIBLE);
nextButton.setVisibility(View.VISIBLE);
//https://stackoverflow.com/questions/45253477/implementing-next-button-in-audio-player-android
nextButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if (stepPosition < stepsArrayList.size() - 1)
{
//Add or subtract the position in 1
stepClicked= stepsArrayList.get(stepPosition);
stepPosition++;
//Using the position, get the current step from the steps list
stepClicked= stepsArrayList.get(stepPosition);
//Extract the video uri from the current step
videoUrl = stepClicked.getVideoUrl();
Log.d("VideoUrlNext: ", stepClicked.getVideoUrl());
videoUrl_Parse = Uri.parse(videoUrl);
//Call initializePlayer() by passing the new video uri
initializePlayer(videoUrl_Parse);
}
}
});
previousButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if (stepPosition> 0)
{
stepPosition--;
//Using the position, get the current step from the steps list
stepClicked= stepsArrayList.get(stepPosition);
//Extract the video uri from the current step
videoUrl = stepClicked.getVideoUrl();
videoUrl_Parse = Uri.parse(videoUrl);
//Call initializePlayer() by passing the new video uri
initializePlayer(videoUrl_Parse);
}
}
});
}
}
if (savedInstanceState != null)
{
stepsArrayList = savedInstanceState.getParcelableArrayList(STEPS_LIST_INDEX);
mPlayerPosition = savedInstanceState.getLong(KEY_POSITION);
}
// Return the root view
return rootView;
}
//ExoPlayer code based on: https://codelabs.developers.google.com/codelabs/exoplayer-intro/#2
public void initializePlayer(Uri videoUrl)
{
if (mExoPlayer == null)
{
TrackSelector trackSelector = new DefaultTrackSelector();
LoadControl loadControl = new DefaultLoadControl();
mExoPlayer = ExoPlayerFactory.newSimpleInstance(getActivity(), trackSelector, loadControl);
mPlayerView.setPlayer((SimpleExoPlayer) mExoPlayer);
String userAgent = Util.getUserAgent(getContext(), "Baking App");
MediaSource mediaSource = new ExtractorMediaSource(videoUrl,
new DefaultDataSourceFactory(getContext(), userAgent),
new DefaultExtractorsFactory(), null, null);
mExoPlayer.prepare(mediaSource);
if (mPlayerPosition != C.TIME_UNSET)
{
mExoPlayer.seekTo(mPlayerPosition);
}
mExoPlayer.setPlayWhenReady(true);
}
}
#Override
public void onStart()
{
super.onStart();
if (Util.SDK_INT > 23 || mExoPlayer == null)
{
initializePlayer(videoUrl_Parse);
}
}
#Override
public void onPause()
{
super.onPause();
if (mExoPlayer != null)
{
mPlayerPosition = mExoPlayer.getCurrentPosition();
}
if (Util.SDK_INT <= 23)
{
releasePlayer();
}
}
#Override
public void onResume()
{
super.onResume();
if ((Util.SDK_INT <= 23 || mExoPlayer == null))
{
mPlayerPosition = mExoPlayer.getCurrentPosition();
}
}
#Override
public void onStop()
{
super.onStop();
if (Util.SDK_INT > 23 || mExoPlayer != null)
{
mExoPlayer.getCurrentPosition();
}
releasePlayer();
}
/**
* Release ExoPlayer.
*/
private void releasePlayer()
{
if (mExoPlayer != null)
{
mPlayerPosition = mExoPlayer.getCurrentPosition();
mExoPlayer.release();
mExoPlayer = null;
}
}
#Override
public void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
//Save the fragment's state here
outState.putParcelableArrayList(STEPS_LIST_INDEX, stepsArrayList);
outState.putLong(KEY_POSITION, mPlayerPosition);
super.onSaveInstanceState(outState);
}
}
Parent Activity:
public class IngredientStepsActivity extends AppCompatActivity implements StepsListFragment.OnStepClickListener
{
private static final String TAG = IngredientStepsActivity.class.getSimpleName();
private Context context;
Recipes recipes;
// Track whether to display a two-pane or single-pane UI
public boolean mTwoPane;
public int stepPosition;
ArrayList<Steps> stepsArrayList;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ingredientsteps);
// Determine if you're creating a two-pane or single-pane display
if (savedInstanceState == null)
{
if (getIntent() != null && getIntent().getExtras() != null)
{
recipes = getIntent().getExtras().getParcelable("Recipes");
if(findViewById(R.id.tablet_detail_layout) != null)
{
// This LinearLayout will only initially exist in the two-pane tablet case
mTwoPane = true;
// Only create new fragments when there is no previously saved state
/*
Add the fragment to its container using a FragmentManager and a Transaction
Send the ingredients array list in Parcelable to the Ingredients Fragment
*/
FragmentManager fragmentManager = getSupportFragmentManager();
Bundle ingredientsBundle = new Bundle();
ingredientsBundle.putParcelable("Recipes", recipes);
//Pass Over the bundle to the Ingredients Fragment
IngredientsFragment ingredientsFragment = new IngredientsFragment();
ingredientsFragment.setArguments(ingredientsBundle);
fragmentManager.beginTransaction().replace(R.id.ingredients_fragment_container, ingredientsFragment).commit();
//Pack Data in a bundle call the bundle "stepsBundle" to differentiate it from the "ingredientsBundle"
Bundle stepsBundle = new Bundle();
stepsBundle.putParcelable("Recipes", recipes);
//Pass Over the bundle to the Steps Fragment
StepsListFragment stepsListFragment = new StepsListFragment();
stepsListFragment.setArguments(stepsBundle);
fragmentManager.beginTransaction().replace(R.id.steps_fragment_container, stepsListFragment).commit();
}
else
{
// We're in single-pane mode and displaying fragments on a phone in separate activities
mTwoPane = false;
FragmentManager fragmentManager = getSupportFragmentManager();
Bundle ingredientsBundle = new Bundle();
ingredientsBundle.putParcelable("Recipes", recipes);
//Pass Over the bundle to the Ingredients Fragment
IngredientsFragment ingredientsFragment = new IngredientsFragment();
ingredientsFragment.setArguments(ingredientsBundle);
fragmentManager.beginTransaction().replace(R.id.ingredients_fragment_container, ingredientsFragment).commit();
//Pack Data in a bundle call the bundle "stepsBundle" to differentiate it from the "ingredientsBundle"
Bundle stepsBundle = new Bundle();
stepsBundle.putParcelable("Recipes", recipes);
//Pass Over the bundle to the Steps Fragment
StepsListFragment stepsListFragment = new StepsListFragment();
stepsListFragment.setArguments(stepsBundle);
fragmentManager.beginTransaction().replace(R.id.steps_fragment_container, stepsListFragment).commit();
}
}
}}
#Override
public void onClick(Steps stepClicked)
{
if (mTwoPane)
{
Bundle stepsVideoBundle = new Bundle();
stepsVideoBundle.putParcelable("Steps", stepClicked);
stepsVideoBundle.putBoolean("TwoPane", mTwoPane);
stepsVideoBundle.putInt("StepPosition", stepPosition);
stepsVideoBundle.putParcelableArrayList("StepsArrayList", stepsArrayList);
VideoFragment videoFragment = new VideoFragment();
videoFragment.setArguments(stepsVideoBundle);
getSupportFragmentManager().beginTransaction().replace(R.id.video_fragment_container, videoFragment).commit();
}
else
{
Log.i("Step: ", stepClicked.getStepShortDescription());
Intent intent = new Intent(IngredientStepsActivity.this, VideoPhoneActivity.class);
intent.putExtra("Steps", stepClicked);
startActivity(intent);
}
}
}
I've been searching everywhere and I can't find the answer. I'm simply trying to enable bluetooth in my fragment. I added the following to lines to my OnResume() callback:
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent,REQUEST_ENABLE_BT);
}
for some reason, the output just keeps saying, Activity.onPostResume() called over and over again and it actually locks out my UI. I was wondering if there's a solution?
Edit: AutoConnectFragment:
public class AutoConnectFragment extends Fragment {
private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
private Toolbar mToolbar;
private CollapsingToolbarLayout collapsingToolbar;
private ImageView mBackArrow;
private Button mStartTiming;
private RecyclerView mLaserRecyclerView;
private LaserAdapter mAdapter;
private String mCurrentEvent;
private BluetoothAdapter mBluetoothAdapter;
private BluetoothLeScanner mBluetoothLeScanner;
private AutoConnectBLE mScanner;
private static boolean mIsLasersConnected;
private Drill mCurrentDrill;
private AutoConnectEventSelected mCallback;
private static final int REQUEST_ENABLE_BT = 3;
private static final int REQUEST_CODE_LOCATION = 42;
private boolean permissionChecked = false;
// Container Activity must implement this interface
public interface AutoConnectEventSelected {
public void onAutoConnectEventSelected(String event);
}
// private nested custom view holder class
public class LaserHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView mLaserName;
private Module mModule;
private ImageView mConnectIcon;
private ProgressBar mProgressBar;
public LaserHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.list_item_laser, parent, false));
itemView.setOnClickListener(this);
// grab the font
Typeface mont_reg = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Montserrat-Regular.ttf");
// grab the user name and change the font
mLaserName = (TextView) itemView.findViewById(R.id.laser_name);
mLaserName.setTypeface(mont_reg);
// grab the progress bar
mProgressBar = (ProgressBar) itemView.findViewById(R.id.progress_bar);
//grab the connect icon
mConnectIcon = (ImageView) itemView.findViewById(R.id.connect_icon);
}
public void bind(Module module) {
// set the text view to the module name
mModule = module;
mLaserName.setText(module.getName());
}
// if the user clicks on the connect laser
#Override
public void onClick(View v) {
if (mModule.getName().equals("RFID")) {
mProgressBar.setVisibility(View.VISIBLE);
mConnectIcon.setVisibility(View.GONE);
// mScanner.scanRFID(mCurrentDrill, mModule.getName(), v, getContext(), mAdapter,getAdapterPosition());
} else {
mProgressBar.setVisibility(View.VISIBLE);
mConnectIcon.setVisibility(View.GONE);
mScanner.scanLaser(v,mCurrentDrill, mModule.getName(),mAdapter,getAdapterPosition());
}
mAdapter.setCurrentPosition(getAdapterPosition());
}
}
public class LaserAdapter extends RecyclerView.Adapter<LaserHolder> {
private List<Module> mModules;
private String mCurrentMAC;
private int mCurrentPosition;
public LaserAdapter(List<Module> modules) {
mModules = modules;
}
#Override
public LaserHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
return new LaserHolder(layoutInflater, parent);
}
#Override
public void onBindViewHolder(LaserHolder holder, int position) {
Module module = mModules.get(position);
/* if a laser is already connected and
the user tries to connect the same laser to another position,
unconnect the previous connection
*/
if (!TextUtils.isEmpty(module.getMACaddress())){
if ( module.getMACaddress().equals(mCurrentMAC) && position != mCurrentPosition){
holder.mConnectIcon.setImageResource(R.drawable.ic_flash);
module.setMACaddress(null);
}
}
checkAllLasersConnected(mModules);
holder.bind(module);
}
#Override
public int getItemCount() {
return mModules.size();
}
public String getCurrentMAC() {
return mCurrentMAC;
}
public void setCurrentMAC(String currentMAC) {
mCurrentMAC = currentMAC;
}
public int getCurrentPosition() {
return mCurrentPosition;
}
public void setCurrentPosition(int currentPosition) {
mCurrentPosition = currentPosition;
}
public void checkAllLasersConnected(List<Module> modules){
int numLasersConnected = 0;
// checking to see if all of the lasers are connected
for (int i = 0; i < modules.size(); i++) {
System.out.println("Name: " + modules.get(i).getName() + " MAC :" + modules.get(i).getMACaddress());
if (modules.get(i).getMACaddress() == null) {
numLasersConnected++;
}
}
// if all of the lasers are connected, enabled the start timing button
if (numLasersConnected == 0) {
mStartTiming.setEnabled(true);
} else {
mStartTiming.setEnabled(false);
}
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
// inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_autoconnect, container, false);
// grab the recyclerview and set its layout manager
mLaserRecyclerView = (RecyclerView) view.findViewById(R.id.list_recycler_view);
mLaserRecyclerView.setLayoutManager((new LinearLayoutManager(getActivity())));
// update the UI ( recycler view )
updateUI(savedInstanceState);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// grab the views
collapsingToolbar = (CollapsingToolbarLayout) view.findViewById(R.id.collapsing_toolbar);
mToolbar = (Toolbar) view.findViewById(R.id.toolbar);
mBackArrow = (ImageView) view.findViewById(R.id.back_arrow);
mStartTiming = (Button) view.findViewById(R.id.start_timing_button);
// disable the startTiming button until all of the lasers are connected
mStartTiming.setEnabled(false);
//Set toolbar title
collapsingToolbar.setTitle(getArguments().getString("Event") + " Connect");
// setting the text alignment
collapsingToolbar.setExpandedTitleColor(Color.WHITE);
collapsingToolbar.setCollapsedTitleGravity(Gravity.CENTER_HORIZONTAL);
collapsingToolbar.setCollapsedTitleTextColor(Color.WHITE);
collapsingToolbar.setExpandedTitleGravity(Gravity.CENTER_HORIZONTAL);
// set the font
Typeface mont_bold = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Montserrat-Bold.ttf");
Typeface mont_regular = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Montserrat-Regular.ttf");
collapsingToolbar.setExpandedTitleTypeface(mont_bold);
collapsingToolbar.setCollapsedTitleTypeface(mont_regular);
// set background color to dark grey
mToolbar.setBackgroundColor(getResources().getColor(R.color.darkGrey));
// set up bluetooth
mScanner = new AutoConnectBLE(getContext());
// collapsing tool bar effect ( explained in main activtiy)
AppBarLayout mAppBarLayout = (AppBarLayout) view.findViewById(R.id.app_bar_layout);
mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int i) {
//measuring for alpha
int toolBarHeight = mToolbar.getMeasuredHeight();
int appBarHeight = appBarLayout.getMeasuredHeight();
Float f = ((((float) appBarHeight - toolBarHeight) + i) / ((float) appBarHeight - toolBarHeight)) * 255;
if (Math.round(f) == 0) {
mToolbar.setBackgroundColor(getResources().getColor(R.color.darkGrey));
} else {
mToolbar.getBackground().setAlpha(0);
}
}
});
// if user clicks on the back arrow, go back to testing page
mBackArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment frag = new TestingFragment();
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.replace(R.id.container, frag, frag.getTag());
ft.addToBackStack(null);
ft.commit();
}
});
// if the user clicks on the start timing, goto the timing page
mStartTiming.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCallback.onAutoConnectEventSelected(getArguments().getString("Event"));
}
});
}
#Override
public void onResume() {
super.onResume();
System.out.println("ON RESUME CALLED");
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
System.out.println("INTENT CALLED");
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
getActivity().startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
//
// if (!getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
// Toast.makeText(getActivity(), "No LE Support, Please install this app on another phone", Toast.LENGTH_SHORT).show();
// return;
// }
}
private void updateUI(Bundle savedInstanceState) {
List<Module> modules = null;
// check to see which event the user chose and grab the laser array list
switch (getArguments().getString("Event")) {
case "Dash":
Dash dash = Dash.getInstance();
modules = dash.getModules();
mCurrentDrill = dash;
break;
case "ProAgility":
ProAgility pa = ProAgility.getInstance();
modules = pa.getModules();
mCurrentDrill = pa;
break;
case "DashSplit":
DashSplit ds = DashSplit.getInstance();
modules = ds.getModules();
mCurrentDrill = ds;
break;
case "Flying40":
Flying40 f = Flying40.getInstance();
modules = f.getModules();
mCurrentDrill = f;
break;
case "Lap":
Lap l = Lap.getInstance();
modules = l.getModules();
mCurrentDrill = l;
break;
}
mAdapter = new LaserAdapter(modules);
mLaserRecyclerView.setAdapter(mAdapter);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
Activity a;
if (context instanceof Activity){
a = (Activity) context;
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (AutoConnectEventSelected) a;
} catch (ClassCastException e) {
throw new ClassCastException(a.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_ENABLE_BT) {
System.out.println(requestCode);
if (resultCode == Activity.RESULT_CANCELED) {
//Bluetooth not enabled.
getActivity().finish();
return;
} else {
return;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
BLE auto connect Scanner class:
public class AutoConnectBLE {
private BluetoothAdapter mBluetoothAdapter;
private BluetoothManager mBluetoothManager;
private BluetoothLeScanner mBluetoothLEScanner;
private ScanSettings mSettings;
private Context mContext;
private long mStartScanTimeStamp;
private long connectTimeStamp = 0L;
private class laserCallBack extends ScanCallback {
private Drill drill;
private AutoConnectFragment.LaserAdapter mAdapter;
private int position;
private boolean isConnected = false;
private long scanTimeStamp = 0L;
private long mElapsedTimeScanning;
private String mHex;
private long mLaserTime;
private String mBeefMessage;
private String name;
private ImageView mConnectIcon;
private ProgressBar mProgressBar;
public laserCallBack(View view, Drill drill,String name, AutoConnectFragment.LaserAdapter mAdapter, int position) {
super();
this.drill = drill;
this.mAdapter = mAdapter;
this.position = position;
this.name = name;
// grab views
mProgressBar = (ProgressBar) view.findViewById(R.id.progress_bar);
mConnectIcon = (ImageView) view.findViewById(R.id.connect_icon);
}
#Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
// grab a timestamp of when the scan starts
scanTimeStamp = SystemClock.uptimeMillis();
// if its been 3 seconds, without scanning then stop
mElapsedTimeScanning = (scanTimeStamp - mStartScanTimeStamp) / 1000;
// if the elapsed time is 3 seconds, then stop the scan
if (mElapsedTimeScanning >= 3) {
if (mConnectIcon.getVisibility() != View.VISIBLE) {
// if nothing was found, stop the circular progress bar and place the lightning bolt
mProgressBar.setVisibility(View.GONE);
mConnectIcon.setImageResource(R.drawable.ic_flash);
mConnectIcon.setVisibility(View.VISIBLE);
// clear out laser
ArrayList<Module> m = drill.getModules();
m.get(position).setMACaddress(null);
}
mAdapter.notifyDataSetChanged();
isConnected = false;
mBluetoothLEScanner.stopScan(this);
} else {
// grabbing important data from byte record
mHex = ConversionHelper
.bytesToHex(result.getScanRecord().getBytes());
mLaserTime = ConversionHelper.
hex2decimal(mHex.substring(24, 32));
mBeefMessage = mHex.substring(32, 36);
/* if there is no connection yet, and the beef message is preset,
and the laser time < 3 seconds,
and its atleast 3 seconds since another laser has advertised,
accept this new scan record as a potential new laser
*/
System.out.println("CONNECTION DELAY:" + (scanTimeStamp - connectTimeStamp));
if (!isConnected
&& ConversionHelper.hex2decimal(mBeefMessage) == 48879
&& mLaserTime < 3000
&& scanTimeStamp - connectTimeStamp > 3000) {
// set isConnected to true
isConnected = true;
// grab second timestamp - used so that people can't connect the same MAC for 2 lasers
connectTimeStamp = SystemClock.uptimeMillis();
System.out.println("CONNECT TIME STAMP" + connectTimeStamp);
// set the MAC address of the laser
drill.setMAC(name, result.getDevice().getAddress());
mAdapter.setCurrentMAC(result.getDevice().getAddress());
mAdapter.notifyDataSetChanged();
// check to see if this laser is connected to another position
// if the device finds a viable laser, replace the circular progress bar with a checkmark
mProgressBar.setVisibility(View.GONE);
mConnectIcon.setImageResource(R.drawable.ic_connected);
mConnectIcon.setVisibility(View.VISIBLE);
// notify the user that the start laser has been connected
Toast message = Toast.makeText(mContext, name + " Connected!", Toast.LENGTH_SHORT);
message.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
message.show();
isConnected = false;
mBluetoothLEScanner.stopScan(this);
}
}
}
}
public AutoConnectBLE(Context context) {
// grab context
mContext = context;
// grab BLE scanner
mBluetoothManager = (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = mBluetoothManager.getAdapter();
mBluetoothLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
// set settings to LOW LATENCY
mSettings = new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.build();
}
public void scanLaser(View view,Drill drill ,String name, final AutoConnectFragment.LaserAdapter mAdapter, int position) {
mStartScanTimeStamp = SystemClock.uptimeMillis();
mBluetoothLEScanner.startScan(new ArrayList<ScanFilter>(), mSettings,new laserCallBack(view, drill, name, mAdapter, position));
}
// public void scanRFID(final Drill drill, final String name, final View v, final Context context, final AutoConnectFragment.LaserAdapter mAdapter, final int position) {
//
// final ScanCallback RFIDCallBack = new ScanCallback() {
// #Override
// public void onScanResult(int callbackType, ScanResult result) {
// super.onScanResult(callbackType, result);
//
// // grab a timestamp
// scanTimeStamp = SystemClock.uptimeMillis();
//
//
// String hex = ConversionHelper
// .bytesToHex(result.getScanRecord().getBytes());
// String RFIDBeefMessage = hex.substring(36, 40);
// System.out.println(hex);
//
// // if its been 3 seconds, without connecting then stop
// mElapsedTimeScanning = (scanTimeStamp - mStartScanTimeStamp) / 1000;
// if (mElapsedTimeScanning == 3) {
// ImageView mConnectIcon = (ImageView) v.findViewById(R.id.connect_icon);
// if (mConnectIcon.getVisibility() != View.VISIBLE) {
//
// // if nothing was found, stop the circular progress bar and place the lightning bolt
// ProgressBar mProgressBar = (ProgressBar) v.findViewById(R.id.progress_bar);
// mProgressBar.setVisibility(View.GONE);
// mConnectIcon.setImageResource(R.drawable.ic_flash);
// mConnectIcon.setVisibility(View.VISIBLE);
//
// }
// System.out.println("STOPPED SCANNING");
// mBluetoothLEScanner.stopScan(this);
// isConnected = false;
// }
//
// // RFID
// if (!isConnected && RFIDBeefMessage.equals("BEEF")) {
// isConnected = true;
// mBluetoothLEScanner.stopScan(this);
//
// // set the MAC address of the laser
// String MACAddress = result.getDevice().getAddress();
// drill.setMAC(name, MACAddress);
// // notify the user that the start laser has been connected
//
// // if the device finds a viable laser, replace the circular progress bar with a checkmark
// ImageView mConnectIcon = (ImageView) v.findViewById(R.id.connect_icon);
// ProgressBar mProgressBar = (ProgressBar) v.findViewById(R.id.progress_bar);
// mProgressBar.setVisibility(View.GONE);
// mConnectIcon.setImageResource(R.drawable.ic_connected);
// mConnectIcon.setVisibility(View.VISIBLE);
// Toast message = Toast.makeText(context, name + " Connected!", Toast.LENGTH_SHORT);
// message.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
// message.show();
//
// }
//
// }
//
// };
// mStartScanTimeStamp = SystemClock.uptimeMillis();
// mBluetoothLEScanner.startScan(new ArrayList<ScanFilter>(), mSettings, RFIDCallBack);
//
//
// }
}
Use below code to enable your bluetooth
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(!mBluetoothAdapter.isEnabled()){
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(getActivity());
alertBuilder.setCancelable(true);
alertBuilder.setMessage("Do you want to enable bluetooth");
alertBuilder.setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mBluetoothAdapter.enable();
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
}
Just add a manifest permission for Bluetooth access.
<uses-permission android:name="android.permission.BLUETOOTH"/>
and add this snippet in your fragment, for run time permission allowance.
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.BLUETOOTH)
!= PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(((Activity)getContext()),
new String[]{Manifest.permission.BLUETOOTH}, REQUEST_CODE);
}
The snippet automatically launch an alert for Bluetooth access.
First get a BluetoothAdapter object
BluetoothAdapter adapter = BluetoothAdapter.getDefaultBluetoothAdapter();
if(adapter != null){
adapter.enable();
}
Using above code you can enable Bluetooth without user permission.I hope this code will help you
I have a code that only takes information from a web vía Jsoup and I want to refresh this information every second. I tried with all the code that I've found in Google and stackoverflow with no luck. Thank you very much in advance. [SOLVED]
Now I'm trying to send an array from MainActivity to another Activity called "Activity_allday" with Bundle and Intent when viewallday() function is called pressing the "btviewallday" button but with no luck. Any suggestions?
LogCat error: Could not find a method viewallday(View) in the activity class com.example.Chispa.MainActivity for onClick handler on view class android.widget.Button with id 'btviewallday'.
I've noticed that the error comes from receiving two values at viewallday(View view, Pair p). How can I receive the "Pair p" value in my viewallday function?
Here is the new app code:
[MainActivity]
public class MainActivity extends Activity {
private TextView tvmax, tvmid, tvmin, tvactualval,tvvaloractual,tvdate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvdate=(TextView)findViewById(R.id.tvdate);
tvvaloractual=(TextView)findViewById(R.id.tvvaloractual);
tvmax=(TextView)findViewById(R.id.tvmaximo);
tvmid=(TextView)findViewById(R.id.tvmedio);
tvmin=(TextView)findViewById(R.id.tvminimo);
new BackGroundTask().execute();
callAsynchronousTask();
}
public void callAsynchronousTask() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
BackGroundTask performBackgroundTask = new BackGroundTask();
// PerformBackgroundTask this class is the class that extends AsynchTask
performBackgroundTask.execute();
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 1000); //execute in every 1000 ms
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class Pair
{
public String[] bar;
public String[] values;
}
public void viewallday(View view, Pair p) {
Intent intent = new Intent(this, Activity_allday.class);
Bundle bundle =new Bundle();
bundle.putStringArray("bar", p.bar);
intent.putExtras(bundle);
startActivity(intent);
}
class BackGroundTask extends AsyncTask<Void, Void, Pair> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
public String[] getValuesGraph(Document doc) {
int cont=24,var=7;
String bar[] = new String[cont];
/*
* Getting elements from the graphic in an array from 0-23. 0 it's 1:00am, 23 it's 00:00am
*/
for (cont=0; cont < 24; cont++){
String onMouseOver = doc.select("a").get(var+cont).attr("onMouseOver");
bar[cont] = onMouseOver.split("'")[9];
}
return bar;
}
public String[] getValuesFooter(Document doc) {
String values[] = new String[7];
/*
* Getting elements from the graphic footer
*/
String delimiters= "[ /]+";
Elements elements = doc.select("td.cabeceraRutaTexto");
elements.size(); // 6
/* Getting text from table */
values[0] = elements.get(0).text(); // TITLE
values[1] = elements.get(1).text(); // TEXT MAX VALUE
values[2] = elements.get(2).text(); // TEXT MIDDLE VALUE
values[3] = elements.get(3).text(); // TEXTO MIN VALUE
/* Getting numbers from table */
values[4] = elements.get(4).text().split(delimiters)[0]; // NUMBER MAX VALUE
values[5] = elements.get(5).text().split(delimiters)[0]; // NUMBER MIDDLE VALUE
values[6] = elements.get(6).text().split(delimiters)[0]; // NUMBER MIN VALUE
return values;
}
#Override
public Pair doInBackground(Void... params) {
Pair p = new Pair();
try {
URL url= new URL("http://www.myweb.com");
Document doc = Jsoup.connect(url.toString()).get();
p.bar = getValuesGraph(doc);
p.values = getValuesFooter(doc);
/*
* Getting elements from the graphic in an array from 0-23. 0 it's 1:00am, 23 it's 00:00am
*/
return p;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public String ActualHourValue() {
Format formatter = new SimpleDateFormat("H");
String onlyhour = formatter.format(new Date());
return onlyhour;
}
public void ShowDateHour(){
Calendar c = Calendar.getInstance();
SimpleDateFormat df3 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss a");
String formattedDate3 = df3.format(c.getTime());
tvdate.setText("Fecha y hora actuales : "+formattedDate3);
}
#Override
protected void onPostExecute(Pair p) {
int hour = Integer.parseInt(ActualHourValue());
tvvaloractual.setText(p.bar[hour]+" €/MWh");
tvmax.setText(p.values[4]+" €/MWh");
tvmid.setText(p.values[5]+" €/MWh");
tvmin.setText(p.values[6]+" €/MWh");
ShowDateHour();
/*super.onPostExecute(p.values);*/
}
}
}
[Activity_allday]
Public class Activity_allday extends MainActivity {
private TextView tvall;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.all_day_prices);
tvall = (TextView) findViewById(R.id.tvall);
Bundle bundle = this.getIntent().getExtras();
String[] bar=bundle.getStringArray("bar");
/*tvall.setText(bar[0]);*/
}
public void back (View view) {
finish();
}
}
i wanna pass a string to all fragment(child) from fragment activity (main), may be this picture can explain what exactly what i want to do
https://dl.dropboxusercontent.com/u/57465028/SC20140205-163325.png
so, from above picture...i wanna pass a string from edittext by press a button to all activity in viewpager....how could i do that?
i tried to follow this code https://stackoverflow.com/a/12739968/2003393 but it can't solved my problem..
please help me...i'm stuck
thank in advance.
here is my code from fragment activity (MainActivity)
public class Swipe_Menu extends FragmentActivity {
//String KeyWord;
//private static final String KEYWORD = "keyword";
private ViewPager _mViewPager;
private ViewPagerAdapter _adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.swipe_menu_image);
Button Back = (Button)findViewById(R.id.account);
ImageButton Search = (ImageButton)findViewById(R.id.search);
EditText Keyword = (EditText)findViewById(R.id.keyword);
final String KeyWord = Keyword.getText().toString();
/**
* Back button click event
* */
Back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
finish();
}
});
setUpView();
setTab();
}
protected void sendValueToFragments(String value) {
// it has to be the same name as in the fragment
Intent intent = new Intent("my_package.action.UI_UPDATE");
intent.putExtra("UI_KEY", KeyWord );
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
and here is my fragment (Child Activity)
public class Store_Swipe extends Fragment {
public static final String ACTION_INTENT = "my_package.action.UI_UPDATE";
String KeyWord;
private TextView kata_keyword;
protected BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(ACTION_INTENT.equals(intent.getAction())) {
String value = intent.getStringExtra("UI_KEY");
updateUIOnReceiverValue(value);
}
}
};
private void updateUIOnReceiverValue(String value) {
// you probably want this:
KeyWord = value;
}
public static Fragment newInstance(Context context) {
Store_Swipe f = new Store_Swipe();
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter filter = new IntentFilter(ACTION_INTENT);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver, filter);
}
#Override
public void onDestroy() {
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(receiver);
super.onDestroy();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/*Bundle bundle = this.getArguments();
KeyWord = bundle.getString("keyword");*/
View view = inflater.inflate(R.layout.store_swipe, container, false);
init(view);
return view;
}
void init(View view) {
kata_keyword = (TextView) view.findViewById(R.id.keyword);
//ImageView image = (ImageView) view.findViewById(R.id.image_error);
kata_keyword.setText(KeyWord);
}
}
You don't have access directly to your fragments that reside in ViewPager so you can't reference them directly.
What I am doing in these cases is send a broadcast message from Activity to Fragments. For this reason register a BroadcatReceiver in the fragment (either in onCreate or onCreateView - your decision)m, set a custom action for that receiver (ex. "my_package.actions.internal.BROADCAST_ACTION"), don't forget to unregister the receiver from complementary method.
When you want to send a message from activity, create an intent with above mentioned action, add the string in intent extra and send the broadcast.
In your receiver's onReceive method (within the fragment), get the String from intent paramter and there you have the string.
Makes sense?
EDIT: To provide some code, below are the changes that I would make for fragment:
public class Store_Swipe extends Fragment {
public static final String ACTION_INTENT = "my_package.action.UI_UPDATE";
protected BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(ACTION_INTENT.equals(intent.getAction())) {
String value = intent.getStringExtra("UI_KEY");
updateUIOnReceiverValue(value);
}
}
};
private void updateUIOnReceiverValue(String value) {
// you probably want this:
kata_keyword.setText(value);
}
String KeyWord;
private TextView kata_keyword;
public static Fragment newInstance(Context context) {
Store_Swipe f = new Store_Swipe();
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter filter = new IntentFilter(ACTION_INTENT);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver, filter);
}
#Override
public void onDestroy() {
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(receiver);
super.onDestroy();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Bundle bundle = this.getArguments();
KeyWord = bundle.getString("keyword");
View view = inflater.inflate(R.layout.store_swipe, container, false);
init(view);
return view;
}
void init(View view) {
kata_keyword = (TextView) view.findViewById(R.id.keyword);
ImageView image = (ImageView) view.findViewById(R.id.image_error);
kata_keyword.setText(KeyWord);
}
}
And this code I would have from activity, the parameter is the value from EditText:
protected void sendValueToFragments(String value) {
// it has to be the same name as in the fragment
Intent intent = new Intent("my_package.action.UI_UPDATE");
intent.putExtra("UI_KEY", value);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
You would call this from the click listener that you would set in onCreate:
findViewById(R.id.button_id).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String valueThatYouWantToSend = null; /// just the value
sendValueToFragments(valueThatYouWantToSend);
}
});
// I think this solution will solved your issue
// In Main activity put your code -----------------------------------
public void onPageSelected(int position)
{
System.out.println("nilesh");
PageOneFragment f = new PageOneFragment();
f.getText();
PageTwoFragment ff = new PageTwoFragment();
ff.setText();
}
//in General Class ------------------------------------------------
public class General
{
public static String name="";
}
// first Fragment ---------------------------------------------
public void getText()
{
General.name = edittext.getText().toString();
}
// second Fragment ----------------------------------------------
public void setText()
{
System.out.println("name**" + General.name);
tv.setText(General.name);
}
I have two major classes in my project. The first is for creating the connection between the client and the server. The second is for switching between activities.
first:
public class MyActivity extends Activity{
private ListView mList;
private ArrayList<String> arrayList;
private MyCustomAdapter mAdapter;
public TCPClient mTcpClient;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
boolean flag = getIntent().getBooleanExtra("flag",false);
arrayList = new ArrayList<String>();
final EditText editText = (EditText) findViewById(R.id.editText);
Button send = (Button)findViewById(R.id.send_button);
Button menu = (Button)findViewById(R.id.button1);
if (flag == true)
{
//relate the listView from java to the one created in xml
mList = (ListView)findViewById(R.id.list);
mAdapter = new MyCustomAdapter(this, arrayList);
mList.setAdapter(mAdapter);
new connectTask().execute("");
Intent myIntent = new Intent(MyActivity.this,Menu.class);
startActivity(myIntent);
}
send.setOnClickListener(new View.OnClickListener() {
// #Override
public void onClick(View view) {
String message = editText.getText().toString();
//clean the listView to 1 item
if (message.equals("clean"))
{
arrayList.removeAll(arrayList);
mList.removeAllViewsInLayout();
}
//add the text in the arrayList
arrayList.add("c: " + message);
//sends the message to the server
if (mTcpClient != null) {
mTcpClient.sendMessage(message);
}
//refresh the list
mAdapter.notifyDataSetChanged();
editText.setText("");
}
});
//change Activity to live screen mode (live)
menu.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent myIntent = new Intent(MyActivity.this, Menu.class);
startActivity(myIntent);
}
});
}
public class connectTask extends AsyncTask<String,String,TCPClient> {
#Override
protected TCPClient doInBackground(String... message) {
//we create a TCPClient object and
mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {
// #Override
//print the message as an Item
public void messageReceived(String message) {
//this method calls the onProgressUpdate
publishProgress(message);
}
});
mTcpClient.run();
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
//in the arrayList we add the messaged received from server
arrayList.add(values[0]);
// notify the adapter that the data set has changed. This means that new message received
// from server was added to the list
mAdapter.notifyDataSetChanged();
}
}
}
the object TCPClient mTcpClient is the major factor in my app. I use it communicate with the server. In addition, even if I switch between activities it is still running properly so I still get info from server even though I am not in that activity.
second:
public class Menu extends Activity
{
public MyActivity myActivity;
public TCPClient mtcp;
protected void onCreate(Bundle savedInstanceState, MyActivity myActivity)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
ImageView action = (ImageView) findViewById(R.id.imageView1);
action.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event)
{
// here I would like to use mTcpClient object mentioned in the first class
return false;
}
});
}
Basically what I need is a help on how to create in the second class reference to the object mTcpClient that is described in the first class.
You are doing it wrong. If you want to use TcpClient class regardless of context it should NOT be related to first Activity. What you should do is to use singleton pattern:
class TcpClient {
protected static TcpClient mInstance = null;
public TcpClient() {
// your init code...
}
public static TcpClient getInstance() {
if( mInstance == null ) {
mInstance = new TcpClient();
}
return mInstance;
}
...
}
and then, whenever you want to use TcpClient you just do:
TcpClient client = TcpClient.getInstance();