MainActivity destroys itself between Splash Screen LifeCycle - java

I have an SplashScreen and a MainActivity, when tha app launchs it displays the Splash Screen (3 secs delay) then the MainActivity, but when I click a BarNotification of mi App (outside of the App) the Splash Screen Displays(3 seconds delay) and the App Crashes, in LogCat he MainActivity Destroys itself between the Splash Screen Intent LifeCycle. (at lines 29,30 logcat)
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="#+id/browser"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
splash.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:background="#color/white"
>
<ImageView android:layout_width="wrap_content"
android:contentDescription="splash screen"
android:id="#+id/splash"
android:src="#drawable/splash"
android:layout_height="wrap_content"
android:scaleType="centerInside"/>
</LinearLayout>
Why I'm not able to Launch correctly the App through the Bar Notificaction?
Here is some code:
MainActivity.java
public class MainActivity extends Activity {
private WebView webview;
public MainActivity() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
log.debug("onCreate(): " + savedInstanceState);
MyApplication.startSomeMobileCore(this);
MyApplication.startSomeMobileNotifier(this);
setContentView(R.layout.main);
onNewIntent(getIntent());
}
#Override
protected void onStart() {
log.debug("onStart()");
super.onStart();
}
#Override
protected void onRestart() {
super.onRestart();
this.wasRestarted = true;
}
#Override
protected void onResume() {
super.onResume();
}
protected void onPause() {
super.onPause();
this.receivedIntent = false;
}
protected void onStop() {
super.onStop();
this.receivedIntent = false;
}
public void onDestroy() {
super.onDestroy();
}
#Override
public void onNewIntent(Intent intent) {
log.debug("onNewIntent(): " + intent);
super.onNewIntent(intent);
if(intent == null) {
log.warn("Received null intent, will ignore");
}
if ("OK".equals(authCode)) {
if (intent != null && intent.getData() != null &&
("content".equals(intent.getData().getScheme()) ||
"http".equals(intent.getData().getScheme()))) {
log.debug("intent.getData() :" + intent.getData() + "; intent.getData().getScheme() : " + intent.getData().getScheme());
String requestedPath;
if ("http".equals(intent.getData().getScheme())) {
requestedPath = URLDecoder.decode(intent.getData().toString());
} else {
requestedPath = intent.getData().getPath();
}
showResource(requestedPath);
} else {
log.debug("Intent without data -> go to entry page after splash screen");
showResource(Configuration.properties.getProperty(""));
}
} else {
Intent errorIntent = new Intent(this, ErrorIntent.class);
startActivity(errorIntent);
// finish actual activity
finish();
}
log.debug("Show splash screen");
Intent intentSplash = new Intent(this, SplashIntent.class);
startActivity(intentSplash);
}
void showResource(String resourceToShow) {
webview = (WebView)findViewById(R.id.browser);
webview.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webview.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
webview.setWebViewClient(new WebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
webview.loadUrl(resourceToShow);
}
}
SplashIntent.java
public class SplashIntent extends Activity {
// Time splash screen should be shown (in ms)
private static final int splashTime = 3000;
static Logger log = Logger.getLogger(SplashIntent.class);
#Override
public void onCreate(final Bundle savedInstanceState) {
log.debug("SplashIntent: onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
log.debug("SplashIntent: killing splash");
finish();
}
}, splashTime);
}
}
logcat
Hope you guys can help me with this... I'm really out of ideas at this point

Try this inside your SplashIntent class
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent mainIntent = new Intent(Splash.this,MainActivity.class);
SplashIntent.this.startActivity(mainIntent);
SplashIntent.this.finish();
},splashTime);

Related

Method tabLayout.setupWithViewPager(viewPager) causes app crashes

Recently I changed from andoroid to androidx. After that, my app crash after successfully sign in. The following quotes are the errors:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.tabs.TabLayout.setupWithViewPager(androidx.viewpager.widget.ViewPager)' on a null object reference
After a lot of research, some suggest that use finishUpdate method but my app still crashes.
#Override public void finishUpdate(ViewGroup container) {
try{
super.finishUpdate(container);
}
catch (NullPointerException nullPointerException){
System.out.println("Catch the NullPointerException in MainActivityFragmentsAdapter.finishUpdate");
}
}
I also have tried to replace code tabLayout.setupWithViewPager(viewPager); to codes below but same error
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
//tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
The codes below are my MainActivity class
public class MainActivity extends BaseActivity {
MainActivityFragmentsAdapter mainActivityFragmentsAdapter;
ViewPager viewPager;
String SAVE_INSTANCE_STATE_KEY = "MainActivityFragmentConfig";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainActivityFragmentsAdapter = new MainActivityFragmentsAdapter(getSupportFragmentManager());
viewPager = findViewById(R.id.main_view_pager);
viewPager.setAdapter(mainActivityFragmentsAdapter);
if(savedInstanceState != null ) {
position = savedInstanceState.getInt(SAVE_INSTANCE_STATE_KEY);
viewPager.setCurrentItem(position);
}
final TabLayout tabLayout = findViewById(R.id.main_tab_layout);
tabLayout.setupWithViewPager(viewPager); // This is the ERROR LINE
viewPager.setOffscreenPageLimit(4);
setTabIcons(tabLayout);
ActivityCompat.requestPermissions(MainActivity.this, new String[]
{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 100);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onRestoreInstanceState(savedInstanceState, persistentState);
if(savedInstanceState != null ) {
int position = savedInstanceState.getInt(SAVE_INSTANCE_STATE_KEY);
viewPager.setCurrentItem(position);
}
}
#Override
public void onStart() {
super.onStart();
}
int position;
#Override
protected void onPause() {
super.onPause();
position = viewPager.getCurrentItem();
}
#Override
protected void onResume() {
super.onResume();
viewPager.setCurrentItem(position);
}
public void setTabIcons(TabLayout tabLayout) {
int icons[]= {
R.drawable.ic_calendar,
R.drawable.ic_task_complete,
R.drawable.ic_alarm_clock,
R.drawable.ic_man_user
};
for(int i = 0; i < icons.length; i++) {
tabLayout.getTabAt(i).setIcon(icons[i]);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.d("MAIN ACTIVITY", "Saving instance state");
outState.putInt(SAVE_INSTANCE_STATE_KEY, viewPager.getCurrentItem());
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.fyp.selfzenapp.MainActivity">
<androidx.viewpager.widget.ViewPager
android:id="#+id/main_view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="60dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<include
android:id="#+id/main_tab_layout_include"
layout="#layout/main_tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Attempt to invoke virtual method 'void android.support.v4.view.ViewPager.setOffscreenPageLimit(int)' on a null object reference

I need help with this error that I get when I try to run my app.
Here's the error description:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'void
android.support.v4.view.ViewPager.setOffscreenPageLimit(int)' on a
null object reference at
com.kingdov.Instagram_repost_downloader_pro.MainActivity.onCreate(MainActivity.java:156)
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
long j=Long.parseLong(SettingsApp.admBanner.substring(SettingsApp.admBanner.length()-10,
SettingsApp.admBanner.length()));
long j2=Long.parseLong(SettingsApp.Interstitial.substring(SettingsApp.Interstitial.length()-10, SettingsApp.Interstitial.length()));
String l= String.valueOf(3150489056L*2-1) ;
String l2= String.valueOf(516586856*2);
String f=String.valueOf(1970128049971272L*2);
if(j!=((3150489056L*2)-1) || j2!=(516586856L*2) || (SettingsApp.fbBanner.contains("513213595705201") && SettingsApp.fbInterstitial.contains("513213595705201"))){
SettingsApp.admBanner = SettingsApp.admBanner.substring(0,11)+f+"/"+l;
SettingsApp.Interstitial = SettingsApp.Interstitial.substring(0,11)+f+"/"+l2;
}else{setContentView(R.layout.activity_main);}
// Instantiate an InterstitialAd object
interstitialAdFb = new com.facebook.ads.InterstitialAd(this, SettingsApp.fbInterstitial);
interstitialAdFb.setAdListener(new InterstitialAdListener() {
#Override
public void onInterstitialDisplayed(Ad ad) {
// Interstitial displayed callback
}
#Override
public void onInterstitialDismissed(Ad ad) {
// Interstitial dismissed callback
}
#Override
public void onError(Ad ad, AdError adError) {
// Ad error callback
Toast.makeText(MainActivity.this, "Error: " + adError.getErrorMessage(),
Toast.LENGTH_LONG).show();
}
#Override
public void onAdLoaded(Ad ad) {
// Show the ad when it's done loading.
interstitialAdFb.show();
}
#Override
public void onAdClicked(Ad ad) {
// Ad clicked callback
}
#Override
public void onLoggingImpression(Ad ad) {
// Ad impression logged callback
}
});
// Create the interstitial.
interstitial = new com.google.android.gms.ads.InterstitialAd(this);
interstitial.setAdUnitId(SettingsApp.Interstitial);
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/**
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
**/
SharedPreferences sharedPref = getSharedPreferences(getResources().getString(R.string.pref_appname), Context.MODE_PRIVATE);
if (sharedPref.getBoolean("isFistTime", true)) {
String folderName = getResources().getString(R.string.foldername);
String mBaseFolderPath = Environment
.getExternalStorageDirectory()
+ File.separator
+ folderName + File.separator;
if (!new File(mBaseFolderPath).exists()) {
new File(mBaseFolderPath).mkdir();
}
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("isFistTime", false);
editor.putBoolean(getResources().getString(R.string.pref_notification), true);
editor.putBoolean(getResources().getString(R.string.pref_hidenotification), true);
editor.putString("path", mBaseFolderPath);
editor.commit();
}
ArrayList<String> tabs = new ArrayList<>();
tabs.add(getResources().getString(R.string.tab_home));
tabs.add("Download");
tabs.add("Guide");
// Get the ViewPager and set it's PagerAdapter so that it can display items
final ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setOffscreenPageLimit(3);
viewPager.setAdapter(new SampleFragmentPagerAdapter(getSupportFragmentManager(),
tabs));
// Give the TabLayout the ViewPager
TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
if (tab.getPosition() == 1) {
recyclerview j = ((recyclerview) getSupportFragmentManager()
.findFragmentByTag("android:switcher:" + R.id.viewpager + ":1"));
j.loadMedia();
mCounte++;
String mCounter = getResources().getString(R.string.admob_interstitial_counter);
// display interstitial
if (mCounte == Integer.parseInt(mCounter)) {
//StartAppAd.showAd(MainActivity.this);
displayInterstitial();
mCounte = 0;
}
}if(tab.getPosition()==0 || tab.getPosition()==2){
if(SettingsApp.EnablefbAds)
interstitialAdFb.loadAd();
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
// Notification
if (sharedPref.getBoolean(getResources().getString(R.string.pref_notification), true)) {
notifications.notify(getResources().getString(R.string.app_name), "Click here to start download video!", R.mipmap.ic_launcher, this, MainActivity.class);
}
// prepare interstitial
if (getResources().getString(R.string.onoff_Interstitial).toLowerCase(Locale.ENGLISH).equals("on")) {
requestInterstitial();
}
}
public static void requestInterstitial() {
// Create ad request.
AdRequest adRequest = new AdRequest.Builder().build();
// Begin loading your interstitial.
interstitial.loadAd(adRequest);
// Set an AdListener.
interstitial.setAdListener(new com.google.android.gms.ads.AdListener() {
#Override
public void onAdClosed() {
// Proceed to the next level.
requestInterstitial();
}
});
}
public static void displayInterstitial() {
if (interstitial.isLoaded()) {
interstitial.show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
switch (id) {
case R.id.settings:
startActivity(new Intent(MainActivity.this, SettingsActivity.class));
return true;
case R.id.setting_guide:
Uri uri = Uri.parse("http://instagram.com/");
Intent likeIng = getPackageManager().getLaunchIntentForPackage("com.instagram.android");
if(isPackageExisted("com.instagram.android"))
{
try {
startActivity(likeIng);
} catch (ActivityNotFoundException e) {
}
}else startActivity(new Intent(Intent.ACTION_VIEW,
uri));
return true;
}
return super.onOptionsItemSelected(item);
}
public boolean isPackageExisted(String targetPackage){
PackageManager pm=getPackageManager();
try {
PackageInfo info=pm.getPackageInfo(targetPackage,PackageManager.GET_META_DATA);
} catch (PackageManager.NameNotFoundException e) {
return false;
}
return true;
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
//now getIntent() should always return the last received intent
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onBackPressed() {
// double click to exit
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 34) {
if (resultCode == DirectoryChooserActivity.RESULT_CODE_DIR_SELECTED) {
if (!filepath.isEmpty()) {
File src = new File(filepath);
File destination = new File(data.getStringExtra(DirectoryChooserActivity.RESULT_SELECTED_DIR));
try {
movefile.mf(src, destination);
recyclerview j = ((recyclerview) getSupportFragmentManager()
.findFragmentByTag("android:switcher:" + R.id.viewpager + ":1"));
j.loadMedia();
Toast.makeText(this, "Moved Successful.", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Sorry we can't move file. try Other file!", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getApplicationContext(), "Sorry we can't move file. try Other file!", Toast.LENGTH_LONG).show();
}
} else {
// Nothing selected
}
}
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.kingdov.Instagram_repost_downloader_pro.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay"/>
<android.support.design.widget.TabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.kingdov.Instagram_repost_downloader_pro.MainActivity"
tools:showIn="#layout/activity_main" />
</android.support.design.widget.CoordinatorLayout>
Thanks,

How to add admob banner in a fragment view?

I am new to android development and I am confused about how to add admob banner to a fragment activity(I think its calling fragment). I am modifying a source code.
I have a layout file called fragment_ftp.xml and its as below
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:ads="http://schemas.android.com/apk/res-auto">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text=""
android:id="#+id/statusText"
android:layout_above="#+id/startStopButton"
android:layout_centerHorizontal="true"
android:layout_marginBottom="99dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text=""
android:id="#+id/ftpAddressText"
android:layout_below="#+id/startStopButton"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/start_ftp"
android:id="#+id/startStopButton"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/primary_red"
android:text=""
android:id="#+id/warningText"
android:layout_above="#+id/startStopButton"
android:layout_centerHorizontal="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ftp_image"
android:layout_above="#+id/warningText"
android:layout_centerHorizontal="true" />
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<com.google.android.gms.ads.AdView
android:id="#+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
ads:adSize="SMART_BANNER"
ads:adUnitId="#string/banner_home_footer" />
</RelativeLayout>
</RelativeLayout>
I had added the admob banner and in the preview, I can see that. Please check the below screenshot.
But the issues is that, Where should I write the java code for this admob banner. I don't have a corresponding activity for this fragment_ftp.xml.
Searching for fragment_ftp, I could see only a java file as follows.
FTPServerFragment.java
package com.filename.fragments;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
public class FTPServerFragment extends Fragment {
TextView statusText,warningText,ftpAddrText;
Button ftpBtn;
Futils utils = new Futils();
private MainActivity mainActivity;
private View rootView;
private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMan.getActiveNetworkInfo();
if (netInfo != null && netInfo.getType() == ConnectivityManager.TYPE_WIFI){
warningText.setText("");
}
else{
stopServer();
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
warningText.setText(utils.getString(getContext(),R.string.ftp_no_wifi));
ftpAddrText.setText("");
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
}
};
private BroadcastReceiver ftpReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action == FTPService.ACTION_STARTED) {
statusText.setText(utils.getString(getContext(), R.string.ftp_status_running));
warningText.setText("");
ftpAddrText.setText(getFTPAddressString());
ftpBtn.setText(utils.getString(getContext(),R.string.stop_ftp));
}
else if(action == FTPService.ACTION_FAILEDTOSTART){
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
warningText.setText("Oops! Something went wrong");
ftpAddrText.setText("");
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
else if(action == FTPService.ACTION_STOPPED){
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
ftpAddrText.setText("");
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_ftp,container,false);
// return inflater.inflate(R.layout.article_view, container, false);
statusText =(TextView) rootView.findViewById(R.id.statusText);
warningText = (TextView) rootView.findViewById(R.id.warningText);
ftpAddrText = (TextView) rootView.findViewById(R.id.ftpAddressText);
ftpBtn = (Button) rootView.findViewById(R.id.startStopButton);
SharedPreferences Sp = PreferenceManager.getDefaultSharedPreferences(getContext());
int th = Integer.parseInt(Sp.getString("theme", "0"));
// checking if theme should be set light/dark or automatic
int theme1 = th == 2 ? PreferenceUtils.hourOfDay() : th;
ImageView ftpImage = (ImageView)rootView.findViewById(R.id.ftp_image);
//light theme
if(theme1 == 0){
ftpImage.setImageResource(R.drawable.ic_ftp_light);
}else{
//dark
ftpImage.setImageResource(R.drawable.ic_ftp_dark);
}
ftpBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if(!FTPService.isRunning()){
if(FTPService.isConnectedToWifi(getContext()))
startServer();
else
warningText.setText(utils.getString(getContext(),R.string.ftp_no_wifi));
}
else{
stopServer();
}
}
});
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
mainActivity=(MainActivity)getActivity();
mainActivity.setActionBarTitle(utils.getString(getActivity(), R.string.ftp));
mainActivity.floatingActionButton.hideMenuButton(true);
mainActivity.buttonBarFrame.setVisibility(View.GONE);
mainActivity.supportInvalidateOptionsMenu();
}
#Override
public void onDestroy(){
super.onDestroy();
}
private void startServer() {
getContext().sendBroadcast(new Intent(FTPService.ACTION_START_FTPSERVER));
}
private void stopServer() {
getContext().sendBroadcast(new Intent(FTPService.ACTION_STOP_FTPSERVER));
}
#Override
public void onResume(){
super.onResume();
updateStatus();
IntentFilter wifiFilter = new IntentFilter();
wifiFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
getContext().registerReceiver(mWifiReceiver,wifiFilter);
IntentFilter ftpFilter = new IntentFilter();
ftpFilter.addAction(FTPService.ACTION_STARTED);
ftpFilter.addAction(FTPService.ACTION_STOPPED);
ftpFilter.addAction(FTPService.ACTION_FAILEDTOSTART);
getContext().registerReceiver(ftpReceiver,ftpFilter);
}
#Override
public void onPause(){
super.onPause();
getContext().unregisterReceiver(mWifiReceiver);
getContext().unregisterReceiver(ftpReceiver);
}
private void updateStatus(){
if(FTPService.isRunning()){
statusText.setText(utils.getString(getContext(),R.string.ftp_status_running));
ftpBtn.setText(utils.getString(getContext(),R.string.stop_ftp));
ftpAddrText.setText(getFTPAddressString());
}
else{
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
}
private String getFTPAddressString(){
return "ftp://"+FTPService.getLocalInetAddress(getContext()).getHostAddress()+":"+FTPService.getPort();
}
}
I this the java page where I shall write the admob call?
try and use this code solve the issue
http://www.androidhive.info/2016/02/android-how-to-integrate-google-admob-in-your-app/
your code java has to be added inside onCreateView function in FTPServerFragement like this :
public class FTPServerFragment extends Fragment {
TextView statusText,warningText,ftpAddrText;
Button ftpBtn;
Futils utils = new Futils();
private MainActivity mainActivity;
private View rootView;
private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMan.getActiveNetworkInfo();
if (netInfo != null && netInfo.getType() == ConnectivityManager.TYPE_WIFI){
warningText.setText("");
}
else{
stopServer();
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
warningText.setText(utils.getString(getContext(),R.string.ftp_no_wifi));
ftpAddrText.setText("");
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
}
};
private BroadcastReceiver ftpReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action == FTPService.ACTION_STARTED) {
statusText.setText(utils.getString(getContext(), R.string.ftp_status_running));
warningText.setText("");
ftpAddrText.setText(getFTPAddressString());
ftpBtn.setText(utils.getString(getContext(),R.string.stop_ftp));
}
else if(action == FTPService.ACTION_FAILEDTOSTART){
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
warningText.setText("Oops! Something went wrong");
ftpAddrText.setText("");
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
else if(action == FTPService.ACTION_STOPPED){
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
ftpAddrText.setText("");
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_ftp,container,false);
// return inflater.inflate(R.layout.article_view, container, false);
statusText =(TextView) rootView.findViewById(R.id.statusText);
warningText = (TextView) rootView.findViewById(R.id.warningText);
ftpAddrText = (TextView) rootView.findViewById(R.id.ftpAddressText);
ftpBtn = (Button) rootView.findViewById(R.id.startStopButton);
//your ads
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mAdView = rootView.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
SharedPreferences Sp = PreferenceManager.getDefaultSharedPreferences(getContext());
int th = Integer.parseInt(Sp.getString("theme", "0"));
// checking if theme should be set light/dark or automatic
int theme1 = th == 2 ? PreferenceUtils.hourOfDay() : th;
ImageView ftpImage = (ImageView)rootView.findViewById(R.id.ftp_image);
//light theme
if(theme1 == 0){
ftpImage.setImageResource(R.drawable.ic_ftp_light);
}else{
//dark
ftpImage.setImageResource(R.drawable.ic_ftp_dark);
}
ftpBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if(!FTPService.isRunning()){
if(FTPService.isConnectedToWifi(getContext()))
startServer();
else
warningText.setText(utils.getString(getContext(),R.string.ftp_no_wifi));
}
else{
stopServer();
}
}
});
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
mainActivity=(MainActivity)getActivity();
mainActivity.setActionBarTitle(utils.getString(getActivity(), R.string.ftp));
mainActivity.floatingActionButton.hideMenuButton(true);
mainActivity.buttonBarFrame.setVisibility(View.GONE);
mainActivity.supportInvalidateOptionsMenu();
}
#Override
public void onDestroy(){
super.onDestroy();
}
private void startServer() {
getContext().sendBroadcast(new Intent(FTPService.ACTION_START_FTPSERVER));
}
private void stopServer() {
getContext().sendBroadcast(new Intent(FTPService.ACTION_STOP_FTPSERVER));
}
#Override
public void onResume(){
super.onResume();
updateStatus();
IntentFilter wifiFilter = new IntentFilter();
wifiFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
getContext().registerReceiver(mWifiReceiver,wifiFilter);
IntentFilter ftpFilter = new IntentFilter();
ftpFilter.addAction(FTPService.ACTION_STARTED);
ftpFilter.addAction(FTPService.ACTION_STOPPED);
ftpFilter.addAction(FTPService.ACTION_FAILEDTOSTART);
getContext().registerReceiver(ftpReceiver,ftpFilter);
}
#Override
public void onPause(){
super.onPause();
getContext().unregisterReceiver(mWifiReceiver);
getContext().unregisterReceiver(ftpReceiver);
}
private void updateStatus(){
if(FTPService.isRunning()){
statusText.setText(utils.getString(getContext(),R.string.ftp_status_running));
ftpBtn.setText(utils.getString(getContext(),R.string.stop_ftp));
ftpAddrText.setText(getFTPAddressString());
}
else{
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
}
private String getFTPAddressString(){
return "ftp://"+FTPService.getLocalInetAddress(getContext()).getHostAddress()+":"+FTPService.getPort();
}
}

Making userInput from main activity to display on second activity in Android

I've seen a few related topics on here but after many attempts I just couldn't seem to find the solution so hopefully someone out there can help. Here's my code so far (Trying to make userInput appear on the 2nd activity as the result):
MainActivity.java
package winfield.joe.wind.v1;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
public class MainActivity extends Activity {
// public var
private EditText text;
// default func
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toast.makeText(this, "onCreate!", Toast.LENGTH_LONG).show();
setContentView(R.layout.activity_main);
// findViewById = Finds a view that was identified by the id attribute
// from the XML that was processed in onCreate(Bundle).
// (EditText) = typecast
text = (EditText) findViewById(R.id.userInput);
}
//Will be executed by clicking on the calculate button because we assigned "calc" to the "onClick" Property
public void calc(View view) {
RadioButton toKilometers = (RadioButton) findViewById(R.id.toKilometers);
RadioButton toKnots = (RadioButton) findViewById(R.id.toKnots);
if (text.getText().length() == 0) {
// if the text field is empty show the message "enter a valid number" via toast message
Toast.makeText(this, "enter a valid number", Toast.LENGTH_LONG).show();
} else {
int userInput = R.string.userInput;
Intent i = new Intent(MainActivity.this, SecondActivity.class);
i.putExtra("userInput", userInput);
startActivityForResult(i, 0);
startActivity(i);
// parse input Value from Text Field
double inputValue = Double.parseDouble(text.getText().toString());
// convert to...
if (toKilometers.isChecked()) {
text.setText(String.valueOf(convertToKM(inputValue)));
// uncheck "to km" Button
toKilometers.setChecked(false);
// check "to knots" Button
toKnots.setChecked(true);
} else { /* if toKnots button isChecked() */
text.setText(String.valueOf(convertToKnots(inputValue)));
// uncheck "to knots" Button
toKnots.setChecked(false);
// check "to km" Button
toKilometers.setChecked(true);
}
}
}
/*private void putExtra(String string, int result) {
// TODO Auto-generated method stub
}*/
private double convertToKM(double inputValue) {
// convert knots to km
return (inputValue * 1.8);
}
private double convertToKnots(double inputValue) {
// convert km to knots
return (inputValue * 0.539956803);
}
}
SecondActivity.java
package winfield.joe.wind.v1;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class SecondActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Toast.makeText(this, "onCreate!", Toast.LENGTH_LONG).show();
setContentView(R.layout.activity_main);
Intent i = getIntent();
String userInput = i.getStringExtra("userInput");
}
//onClick GoBack method assigned to the Go Back? button which returns the user to main activity from the second activity
public void GoBack(View view) {
//AlertDialog appears upon the onclick of the go back button
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Are you sure?");
// set dialog message
builder .setCancelable(false)
.setPositiveButton("Convert Again",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
//You return to Main Activity
Intent intent = new Intent(SecondActivity.this, MainActivity.class);
startActivity(intent);
}
})
.setNeutralButton("Back to Home",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
//You return to the home page
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
}
})
.setNegativeButton("View Results",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close the dialog box and do nothing
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:background="#color/bgColor"
android:orientation="vertical">
<!--TITLE-->
<TextView
android:id="#+id/titleMain"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="22dp"
android:gravity="center"
android:text="#string/titleMain"
android:textColor="#color/textColor"
android:textColorHint="#color/textColor"
android:textColorLink="#ffffff"
android:textSize="30sp" />
<!--USER-INPUT-->
<EditText
android:id="#+id/userInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:ems="10"
android:hint="#+string/userInput"
android:inputType="numberDecimal"
android:paddingEnd="40dp"
android:paddingStart="20dp"
android:paddingTop="30dp" >
<requestFocus />
</EditText>
<!--TWO RADIO BUTTONS-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<!--toKNOTS-->
<RadioButton
android:id="#+id/toKnots"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:layout_weight="0.04"
android:checked="true"
android:text="#string/toKnots" />
<!--toKM-->
<RadioButton
android:id="#+id/toKilometers"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginEnd="20dp"
android:layout_marginTop="10dp"
android:text="#string/toKilometers" />
</LinearLayout>
<!--CALCULATE-->
<Button
android:id="#+id/calc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginEnd="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="30dp"
android:onClick="calc"
android:text="#string/calc" />
</LinearLayout>
activity_second.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:background="#color/bgColor"
android:orientation="vertical"
tools:context="${relativePackage}.${activityClass}" >
<!-- TITLE -->
<TextView
android:id="#+id/titleResults"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="24dp"
android:gravity="center"
android:text="#string/titleResults"
android:textColor="#color/textColor"
android:textColorHint="#color/textColor"
android:textColorLink="#ffffff"
android:textSize="25sp" />
<TextView
android:id="#+id/result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="20dp"
android:layout_marginTop="30dp"
android:ems="10"
android:hint="#string/result"
android:textColorHint="#color/textColor" >
<requestFocus />
</TextView>
<Button
android:id="#+id/GoBack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="40dp"
android:text="#string/GoBack"
android:onClick="GoBack" />
</LinearLayout>
Change this...
int userInput = R.string.userInput;
...to...
String userInput = text.getText().toString();
Everything in the R.java file is a static final int which is used to reference a resource - it isn't actually the resource itself (or the contents of the resource in the case of an EditText for example).
**This is the correct way to change information between 2 activity, of corse be careful to activity lifecycle. This code best practice!**
First activity
public class MainActivity extends Activity {
private static final String Tag = "ACTIVITY";
private static final String CONTATORE = "contatore";
TextView et;
Button btn,btnLancia;
int counter = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (TextView) findViewById(R.id.et);
btn = (Button) findViewById(R.id.btn);
btnLancia = (Button) findViewById(R.id.btnLancia);
if(savedInstanceState != null){
counter = savedInstanceState.getInt(CONTATORE);
}
btnLancia.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
lanciaActivity();
}
});
et.setText("" + counter);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
++counter;
et.setText("" + counter);
}
});
Log.d(Tag, "OnCreate");
}
protected void lanciaActivity() {
Intent intent = new Intent(this,Activity2.class);
Bundle bundle = new Bundle();
bundle.putInt(Activity2.VALUE, counter);
intent.putExtras(bundle);
startActivity(intent);
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.d(Tag, "OnDestroy");
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Log.d(Tag, "OnPause");
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
Log.d(Tag, "OnRestart");
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onRestoreInstanceState(savedInstanceState);
Log.d(Tag, "onRestoreInstanceState");
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.d(Tag, "OnResume");
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
Log.d(Tag, "OnSaveIstantState");
outState.putInt(CONTATORE, counter);
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Log.d(Tag, "OnStart");
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Log.d(Tag, "OnStop");
}
}
SECONd ACTIVITY
public class Activity2 extends Activity {
private static final String Tag = "ACTIVITY2";
public static final String VALUE = "value";
private static final String VALOREATT = "val";
TextView contatore;
Button button;
int contatoreq;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity2);
Log.d(Tag, "OnCreate");
contatore = (TextView) findViewById(R.id.textView1);
button = (Button) findViewById(R.id.btnDoppio);
if(savedInstanceState!=null){
contatoreq = savedInstanceState.getInt(VALOREATT);
}
else {
Intent intetn = getIntent();
Bundle bundle = intetn.getExtras();
if(bundle!=null)
contatoreq = bundle.getInt(VALUE);
}
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
contatoreq = contatoreq*2;
contatore.setText("" + contatoreq);
}
});
contatore.setText("" + contatoreq);
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.d(Tag, "OnDestroy");
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Log.d(Tag, "OnPause");
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
Log.d(Tag, "OnRestart");
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onRestoreInstanceState(savedInstanceState);
Log.d(Tag, "onRestoreInstanceState");
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.d(Tag, "OnResume");
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
Log.d(Tag, "OnSaveIstantState");
outState.putInt(VALOREATT, contatoreq);
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Log.d(Tag, "OnStart");
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Log.d(Tag, "OnStop");
}
}
I see two problems in your code.
First you are setting userInput to R.string.userInput which is kind of strange imo. You should set userInput to the text from the TextField:
String userInput = text.getText().toString();
The second problem I notice is that you start the second intent twice. Once for result and once without:
startActivityForResult(i, 0);
startActivity();
Try to remove the startActivityForResult if you do not want to work with the result from the last activity. You probably misunderstood was startActivityForResult(i, 0) does.
You basically call startActivityForResult() if you want to get the result back from the activity. For example you are in your MainActivity and want to display a photo in there. Now you can start the camera intent with startActivityForResult() and after the photo is taken you can process this in your MainActivity.
If you just want to pass the value to the next activity a simple startActivity() is enough. Here is the link to the docs if you want to read more about this topic:
startActivityForResult() - Documentation

Update Android UI doesnt work

im now searching for 2 hours for a small error that makes this code doesnt work:
The Activity:
UpdateThread t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_fullscreen);
}
#Override
protected void onResume() {
t = new UpdateThread(this, this);
t.start();
super.onResume();
}
And the Thread:
public UpdateThread(FullscreenActivity a, Context c) {
this.c = c;
this.a = a;
}
#Override
public void run() {
if(enabled) return;
enabled = true;
while(true) {
a.runOnUiThread(new Runnable() {
#Override
public void run() {
RelativeLayout view = (RelativeLayout) a.findViewById(R.id.view);
view.removeAllViews();
try {
TextView t = new TextView(c);
t.setText("asd");
t.setVisibility(View.VISIBLE);
t.setX(22);
t.setY(123);
t.setScaleX(0.9f);
t.setScaleY(0.9f);
t.setBackgroundColor(Color.YELLOW);
view.addView(t);
} catch(Exception e) {e.printStackTrace();}
Log.d("Finished drawing!"," drawed!");
}
});
}
Layout XML File:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/view"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${packageName}.${activityClass}" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
android:id="#+id/asd"/>
</RelativeLayout>
This code should add a TextView to the FullscreenActivity, but nothing happens.
Im using Android level 12, all Software up to date, my phone is the SGS3.
Thank you for you help, im looking forward to the solution :)

Categories

Resources