public void doSomething(View view) {
String url, link_url, pro;
url = textIn.getText().toString();
pro = spin.getSelectedItem().toString();
c1 = new ConnectInternetClass(this);
if (!url.isEmpty()) {
if (url.contains(".") && !(url.contains(" "))) {
if (url.split("\\.").length > 1) {
if (checkConnection()) {
link_url = pro+url;
c1.execute(link_url);
} else {
Toast.makeText(this, "check your internet connection", Toast.LENGTH_SHORT).show();
myText.setText("No Internet Connection");
}
} else {
myText.setText("Unknown domain");
}
} else {
myText.setText("Invalid URL");
}
} else {
myText.setText("URL can\'t empty");
}
}
I have that code to show a web page source. I want to show the result in another activity, but I don't know how. I use the create object from the first activity, but it's not method
public class ShowActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show);
MainActivity ma = new MainActivity();
}
Passing data from a activity , linkUrl is your variable which data you want to pass :
Intent intent = new Intent (YourActivity.this, ShowActivity.class) ;
intent.putExtra("KEY_LINK" , linkUrl);
startActivity(intent);
Receiving data from ShowActivity , Access the data by the key in onCreate():
String url = getIntent().getStringExtra("KEY_LINK");
Link : How do I pass data between Activities in Android application?
Link : https://developer.android.com/training/basics/firstapp/starting-activity.html
Why you use this kind of things. If you want to load a web page in an activity use webview for it. no need two activities to do that. Another way you can create a class which has your doSomething method (it should be public static) and call it from an activity by using that's class object. When you coding don't create unnecessary activities.
Related
I´m pretty new in android. I have made communication between two Apps with BroadcastReceiver and intentServices .
The thing is, I want to send information to the app2 from app1. In app1 I need to access a variable which is in MainActivity.class , I need to send it to servicev.class (the service where the intent is handled) but the variable "res" is null when I access it, why does that happen? (App2 calls app1 onHandleIntent and it breaks in res.getOtp() ) I try to create an extra setter getter class and also an intent but getIntent() does not work inside onHandleIntent... how can I achieve to pass res.getOTP (string) ? I really dont want to use SQLite
servicev:
public class servicev extends IntentService {
private static final int RESULT_OK = 1;
protected ResultReceiver mReceiver;
public servicev() {
super("yeah");
}
#Override
protected void onHandleIntent(Intent intent) {
//I receive here the intent from app2 and I need to response with res.getOTP()
helper h = new helper();
String val = intent.getStringExtra("foo");
Intent in = new Intent("com.banorte.bem.movil.veriToken.SendBroadcast");
in.putExtra("resultCode", this.RESULT_OK);
in.putExtra("resultValue", "My Result Value. Passed in: " + h.getRes().getOtp()); //h here is null... setter and getter approach does not work... maybe sqlite could work but it is necesary?
sendBroadcast(in);
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
VTTokenAPI api;
TextView textView;
Button button;
EditText input;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidSetup.getInstance().init(this);
helper h = new helper();
api = new VTTokenAPI("FFFFFF");
res = api.getStatus();
res.getOtp(); //correct value
h.setRes(res);
setContentView(R.layout.activity_main);
}
}
helper:
public class helper {
public VTResult getRes() {
return res;
}
public void setRes(VTResult res) {
this.res = res;
}
VTResult res;
}
You are trying to instantiate a new MainActivity which is not the same as the running activity but a new instance.
If you need your IntentService to be able to get data from a running Activity you have options such as using SharedPreferences or SQLite. Instead of keeping the data in memory try to persist it in some database in the onCreate and then try to read it from the storage during handleIntent
I'm trying to make an dynamical move activity process by using baseActivity through process of defined string value.
But I've faced an problem of "activity is not an enclosing class." error in calling "newIntent.setClassName" method of baseActivity.
Could you help some idea?
First, for explaining about the trying code,
This process purpose is for user sign up process.
Here is used activities.
1. AgreeChildActivity (agree a service terms)
2. VerifyingChildActivity (verifying an user)
3. InputChildActivity (input an user info)
4. CompleteChildActivity (show a service join completed)
1~4 These are children of "GateBaseActivity".
It starts the dynamical move process by onClick method of an "MainActivity".
MainActivity {
String sProcessCase1 = "verifying->input->complete";
String sProcessCase2 = "input->verifying->complete";
String sProcessCase3 = "input->complete";
:
:
public void onClick(View v) {
Intent intent = null;
try {
switch (v.getId()) {
case R.id.goDynamicMenu:
// start dynamic process
Intent newIntent = new Intent()
newIntent.setClassName(this, "AgreeChildActivity");
newIntent.putExtra("MOVE_SEQ", sProcessCase1); <== set processCase.
startActivity(newIntent);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
// Following is each activities code.
GateBaseActivity (<= This is a parent of all process activity.)
void onResume() { (so executes this method when each process activity shows.)
String sActivitySeq = getintent("MOVE_SEQ"); <= "verifying->input->complete"
String sNextActivity = <= calculate the nextActivity name on sActivitySeq. For simple, omitted.
// "verifying->input->complete"
// verifying => VerifyingChildActivity
// input => InputChildActivity
// complete => CompleteChildActivity
String sThisChildSimpleName = this.getClass().getSimpleName();
Intent newIntent = new Intent();
// execute here when childActivity is the "AgreeChildActivity".
if ("AgreeChildActivity".equals(sThisChildSimpleName)) {
newIntent.setClassName(AgreeChildActivity(<=Here occured "not an enclosing class err.", How to solve this error?).this, sNextActivity);
}
// execute here when childActivity is the "VerifyingChildAcitivty".
else if ("VerifyingChildActivity".equals(sThisChildSimpleName)) {
newIntent.setClassName(VerifyingChildActivity(<=Here occured "not an enclosing class err.", How to solve this error?).this, sNextActivity);
}
// execute here when childActivity is the "InputChildAcitivty".
else if ("InputChildActivity".equals(sThisChildSimpleName)) {
newIntent.setClassName(InputChildActivity(<=Here occured "not an enclosing class err.", How to solve this error?).this, sNextActivity);
}
// execute here when childActivity is the "CompleteChildActivity".
else if ("CompleteChildActivity".equals(sThisChildSimpleName)) {
newIntent.setClassName(CompleteChildActivity(<=Here occured "not an enclosing class err.", How to solve this error?).this, sNextActivity);
}
newIntent.putExtra("MOVE_SEQ", sActivitySeq);
startActivity(intent);
}
// These are child activities of "GateBaseActivity".
AgreeChildActivity implement GateBaseActivity
void onResume() {
super.onResume();
Log.d("autoTest", "Here is AgreeChildActivity.");
}
VerifyingChildActivity implement GateBaseActivity
void onResume() {
super.onResume();
Log.d("autoTest", "Here is VerifyingChildActivity.");
}
InputChildActivity implement GateBaseActivity
void onResume() {
super.onResume();
Log.d("autoTest", "Here is InputChildActivity.");
}
CompleteChildActivity implement GateBaseActivity
void onResume() {
super.onResume();
Log.d("autoTest", "Here is CompleteChildActivity.");
}
Try-
Context context = getApplicationContext();
Intent intent = new Intent(context, AgreeChildActivity.class);
You have to use existing activity context to start new activity, new activity is not created yet, and you cannot use its context or call methods upon it.
not an enclosing class error is thrown because of your usage of this keyword. this is a reference to the current object — the object whose method or constructor is being called. With this you can only refer to any member of the current object from within an instance method or a constructor.
I am having hard time doing a task which is supposed to be easy. I am not sure whether it is because of the Android platform's bad design or if I am missing something. I simply would like to refresh a fragment's view on resume. Here are the details:
I have two activities, a SplashActivity which retrieves data from a server (using a AsyncTask) and passes the data to my MainActivity. In my MainActivity, I get this data and pass it to a fragment named SummaryFragment. I have a few fragments and a navigation drawer (in my MainActivity). The first visible fragment is the SummaryFragment which reads the data passed to it from the MainActivity and consequently draws a graph.
When the app starts, there might be no active Internet connection, in that case, in my summary fragment I ask the user to enable WiFi. What I want to do is to refresh this SummaryFragment's view after the user comes back to the app after enabling WiFi. What I do right now is that in the onResume() of my MainActivity, I check if the SummaryFragment in visible, and if so, I start the SplashActivity again (and close the current activity). SplashActivity must fetches the data (like it does when the app starts) and start the MainActivity (fed with the fetched data) which loads the summary fragment and shows the graph.
The problem is that it takes a considerably long time (30-40 seconds) after the app is resumed to go from the SplashActivity to the MainActivity and show the graph (meanwhile the users sees the splash screen), whereas when the app starts it takes 1-2 seconds to do so. Before using the current solution (redirecting user to the SplashActivity), in MainActivity.onResume() I tried using the same AsyncTask class that I am using in the SplashScreen to fetch the data and show the summary fragment afterwards, but the result is the same, there is a significant delay.
The following code is my MainActivity's onResume():
Fragment fragment = getVisibleFragment();
if (fragment instanceof SummaryFragment) {
Intent intentSplashActvity = new Intent(this, SplashActivity.class);
Log.d(TAG, "about to start the splash activity");
startActivity(intentSplashActvity);
// close current activity
finish();
super.onResume();
return;
}
super.onResume();
The SplashActivity:
public class SplashActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
new PrefetchData(this).execute();
}
}
The PrefetchData:
public class PrefetchData extends AsyncTask<Void, Void, Void> {
String serverResponseJson = null;
private String data1 = null,
data2 = null,
data3 = null;
private SplashActivity mSplashActivity = null;
private MainActivity mMainActivity;
public PrefetchData(Activity sourceActivity){
if (sourceActivity.getClass() == SplashActivity.class) {
mSplashActivity = (SplashActivity) sourceActivity;
}
}
#Override
protected Void doInBackground(Void... arg0) {
JsonParser jsonParser = new JsonParser();
try {
if (CaratApplication.isInternetAvailable()) {
serverResponseJson = jsonParser
.getJSONFromUrl("http://aURL");
}
} catch (Exception e) {
Log.d("SplashActivity", e.getStackTrace().toString());
}
if (serverResponseJson != null && serverResponseJson != "") {
try {
JSONArray jsonArray = new JSONObject(serverResponseJson).getJSONArray("arrayName");
// Using Java reflections to set fields by passing their name to a method
try {
setFieldsFromJson(jsonArray, 0, "data1");
setFieldsFromJson(jsonArray, 1, "data2");
setFieldsFromJson(jsonArray, 2, "data3");
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
}
} catch (JSONException e) {
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (mSplashActivity != null) {
Intent intentMainActvity = new Intent(mSplashActivity, MainActivity.class);
if (gotDataSuccessfully()) {
intentMainActvity.putExtra("data1", data1);
intentMainActvity.putExtra("data2", data2);
intentMainActvity.putExtra("data3", data3);
} else {
intentMainActvity.putExtra("data1", Constants.DATA_NOT_AVAIABLE);
intentMainActvity.putExtra("data2", Constants.DATA_NOT_AVAIABLE);
intentMainActvity.putExtra("data3", Constants.DATA_NOT_AVAIABLE);
}
mSplashActivity.startActivity(intentMainActvity);
mSplashActivity.finish();
}
}
}
In MainActivity, upon selection of the "summary" entry in the navigation drawer, I initialize the SummaryFragment, and then replace it using a fragment transaction (replaceFragment(mSummaryFragment, mSummaryFragmentLabel)). Here is the method I use to initialize the summary fragment:
private void initSummaryFragment() {
if (mData1 == 0 && mData2 == 0 && mData3 == 0) {
Intent intent = getIntent();
String data1 = intent.getStringExtra("data1");
String data2 = intent.getStringExtra("data2");
String data3 = intent.getStringExtra("data3");
boolean isDataAvaiable = !data1.equals(Constants.DATA_NOT_AVAIABLE)
&& !data2.equals(Constants.DATA_NOT_AVAIABLE) && !data3.equals(Constants.DATA_NOT_AVAIABLE);
if (isDataAvaiable) {
mData1 = Integer.parseInt(data1);
mData2 = Integer.parseInt(data2);
mData3 = Integer.parseInt(data3);
}
}
mSummaryFragment = new SummaryFragment();
mArgs = new Bundle();
mArgs.putInt("data1", mData1);
mArgs.putInt("data2", mData2);
mArgs.putInt("data3", mData3);
mSummaryFragment.setArguments(mArgs);
mSummaryFragmentLabel = getString(R.string.summary);
}
The SummaryFragment can now retrieve the data it needs from the bundle passed to it.
The problem was with the (rather) undocumented behavior of Android's AsyncTask. An AsyncTask does not run in a separate thread, it runs in a thread that is shared with other AsyncTasks, so if you have other AsyncTasks (or even a plain thread), if they start running before your current AsyncTask, this AsyncTask waits for them to complete their action. I explicitly specified that I would like my AsyncTask to run in a separate thread, and this reduced the delay from about 20-25 seconds to 3-4 seconds for fetching a JSON object (I have other network access calls in progress in parallel). I run the following code as part of my preInitFragments() method in onCreate() method of my main activity.
// The following PrefetchData class is of type AsyncTask<void, void, void>. I moved this class from a stand-alone class to an inner class inside my main activity for easier refreshing of my fragment.
PrefetchData prefetchData = new PrefetchData();
// run this asyncTask in a new thread [from the thread pool] (run in parallel to other asyncTasks)
// (do not wait for them to finish, it takes a long time)
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB)
prefetchData.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
else
prefetchData.execute();
After this I call my method initSummaryFragment(). Please note that in my AsyncTask, in doInBackGround(), I set the two fields (mField1 and mField2) you see below (I used to pass them as a bundle to the summary screen, but that way would cause a problem when you were just detaching and attaching the fragment (to refresh its view) without passing a bundle to your fragment). In the onPostExecute() of my asyncTask, I invoke my method refreshSummaryFragment():
private boolean isStatsDataAvailable() {
return mWellbehaved != 0 && mHogs != 0 && mBugs != 0;
}
private void initSummaryFragment() {
if (! isStatsDataAvailable()) {
mSummaryFragment = new SummaryFragment();
}
mSummaryFragmentLabel = "Summary";
}
For refreshing my summary fragment, I simply detach, and attach my summary fragment, and then commit the pending fragment transaction:
public void refreshSummaryFragment() {
if (isStatsDataAvailable()) { // blank summary fragment already attached. detach and attach to refresh
FragmentManager manager = getSupportFragmentManager();
// init the fragment (for later use when user selects an item from the navigation drawer)
mSummaryFragment = getSupportFragmentManager().findFragmentByTag("Summary");
FragmentTransaction fragTransaction = manager.beginTransaction();
// refresh the summary fragment:
fragTransaction.detach(mSummaryFragment);
fragTransaction.attach(mSummaryFragment);
fragTransaction.commit();
} else {
Log.e(TAG, "refreshSummaryFragment(): stats data not avaiable!");
}
}
I have three activities say A B C , from activity A i go to B and and search city and from Activity B iam going to Activity c , in c iam saving something which i put in Async task
and this will be saved in Activit A listview, the problem is after saving in the list when i hit back button i again see the Activity A with not saving the name which i previously saved
private class Savecity extends AsyncTask<city, String, String> {
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result != null && result.equals("sucess")){
Intent intent = new Intent(activity, cityActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);}
}
#Override
protected String doInBackground(city... arg0) {
try {
((CityPreferences) activity.getApplication()).createcity(arg0[0]);
return "sucess";
} catch (Exception e) {
Log.e(TAG, "", e);
return "fail";
}
}
You can implement this from your AndroidManifest.xml file, just add android:noHistory="true" attribute in those <activity> you want
hope this helps..
Actually in your activity C when you are trying to re-call activity A, all you need to do is to clear activity-stack. For example:
Intent i = new Intent(getBaseContext(), Activity_A.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
I have the following code in one activity:
in= new Intent(ThisActivity.this,AnotherActivity.class);
imgarr = new ImageView[55];
imgarr[0]=(ImageView) findViewById(R.id.species3);
imgarr[0].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
b.putString("specno",Integer.toString(0)); in.putExtras(b);
in.setClassName("com.DuckHuntersJournal","com.DuckHuntersJournal._1_TagKillActivity");
startActivity(in);
}
});
And this code in another:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu1tagkill);
if ((savedInstanceState != null) && savedInstanceState.containsKey("specno")) {
Log.e(tag, "intent from species not null");
species.setText(savedInstanceState.getString("specno"));
}
However, savedInstanceState is null.
Why am I not getting any data back from the first activity?
You need to use :
getIntent().getExtras().getString("specno");
in order to get the passed string from the first activity.
EDIT: I'm not sure what you are trying to do... for getting data from another Activity that started the current one you need to use getIntent().getExtras().
For saving your current stat when the Activity goes to background you save the data in the onSaveInstanceState() method and then in the onCreate(Bundle savedInstance) method you get the saved data from the savedInstance parameter.
You'll need to do the following in your receiving Activity:
String species = getIntent().getStringExtra("specno");