I want to calculate the total in the mainActivity and pass it to the second Activity using explicit intent,
i tried this way but id doesn't work, i want to know how to pass the calculated total to the secondActivity
and this is the code:
TextView result_total_Last;
public void calculateTotal(View view) {
EditText number = findViewById(R.id.number_user);
int num = Integer.parseInt(number.getText().toString());
String result_total;
if (radio_days.isChecked()) {
result_total = (""+ (num * 50) );
} else {
result_total = (""+ (num * 1000) );
}
result_total_Last.setText("the total is" + result_total);
}
// and this is the on click method that used to pass to second activity
book_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (ValidateEmailAddress(email)) {
//create intent to pass the values//
String result_intent = result_total_Last.getText().toString();
Intent intent = new Intent(MainActivity.this, Confirmation_interface.class);
intent.putExtra("total", result_intent);
startActivity(intent);
}
}
});
//code of second activity
Intent intent = getIntent();
String total = intent.getStringExtra("total");
TextView Total_result = findViewById(R.id.Total_ET);
Total_result.setText(total);
}
}
Try receiving like this
String total = getIntent().getExtras().getString("total","defaultIfNotPassed");
Related
I'm trying to read a different .txt file (in a raw folder) in a second activity TextView depending on what button is pressed in MainActivity (the previous activity), but it doesn't work. I'm using the .putextras method and here is my code of the MainActivity:
ImageButton but1=(ImageButton) findViewById(R.id.imageButton2);
but1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent int1=new Intent(MainActivity.this,SecondActivity.class);
int1.putExtra("Thistext", "textnumberone");
startActivity(int1);
finish();
}
});
ImageButton but2(ImageButton) findViewById(R.id.imageButton3);
but2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent int2=new Intent(MainActivity.this,SecondActivity.class);
int2.putExtra("Thistext", "textnumbertwo");
startActivity(int2);
finish();
}
});
Here is my code of the SecondActivity with the Bundle..
Bundle extradata = getIntent().getExtras();
TextView tv = (TextView)findViewById(R.id.firsttextView);
vitautori.setText(extradata.getString("Thistext"));
if (extradata.equals("textnumberone")) {
String texttxt = "";
StringBuffer sbuffer = new StringBuffer();
InputStream is = this.getResources().openRawResource(R.raw.file);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try {
while ((texttxt = reader.readLine()) !=null){
sbuffer.append(texttxt + "n");
}
tv.setText(sbuffer);
is.close();
}catch(Exception e) {
e.printStackTrace();
}
}
}
}
You are currently comparing the Bundle data to a string in
if (extradata.equals("textnumberone"))
This will not work, you have to extract the String data first. Try this:
Bundle extradata = getIntent().getExtras();
String textString = extradata.getString("Thistext");
if (textString.equals("textnumberone")) {
One other thing:
You set the String from the Bundle to a (I suppose) TextView in
vitautori.setText(extradata.getString("Thistext"));
but I don't see the initialization of vitautori anywhere. So make sure the it is initialized or this will crash.
When creating the Intent (both places, of course), I suggest you try to set the type to text:
int1.setType("text/plain");
See if this helps.
I have three activites A,B and C,now what i am doing is,From Activity A i am sending one data to B
Activity B
Intent intent=getIntent();
userids= intent.getStringExtra("userid");
System.out.println("USERID BC"+userids);
pname = intent.getStringExtra("names");
occasions = intent.getStringExtra("oca");
System.out.println("OC BC"+occasions);
pics = intent.getStringExtra("photo");
dates = intent.getStringExtra("datess");
realtions = intent.getStringExtra("realations");
friendid = intent.getStringExtra("friendid");
System.out.println("Frnd BC"+friendid+userids);
sendgift=(ImageView)findViewById(R.id.wishfriend_sendgift);
ImageView propic=(ImageView)findViewById(R.id.wishfriend_propic);
username=(TextView)findViewById(R.id.wishfriend_name);
ocasions=(TextView)findViewById(R.id.wishfriend_occasion);
datess=(TextView)findViewById(R.id.wishfriend_dates);
pointshori=(HorizontalScrollView)findViewById(R.id.pointshori);
yourLayout = (LinearLayout)findViewById(R.id.linearhori);
selectedpoints=(TextView)findViewById(R.id.wishfrindselectdpoints);
username.setText(pname);
ocasions.setText(occasions);
datess.setText("Date: " + dates);
aQuery.id(propic).image(pics, true, true, 0, R.drawable.male);
PLACE_URL = "http:///webservices/wish_friend.php?user_id="+userids+"&det="+friendid+"&occ="+ URLEncoder.encode(realtions);
WISHU_URL = "http:///webservices/wish_friend.php?user_id="+userids;
sendgift.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(edtmessages.getText().toString().trim().equals(""))
{
Toast.makeText(getApplicationContext(),"Enter Message",Toast.LENGTH_SHORT).show();
}
else if(giftpointss.toString().equals("0"))
{
Toast.makeText(getApplicationContext(),"Sorry you can not gift with 0 points",Toast.LENGTH_SHORT).show();
}
else
{
new AttemptLogin().execute();
}
}
});
new LoadAllPreset().execute();
new LoadPlacestatus().execute();
that is working fine,now i am going to B to C,but when i come back from C to B my app got crash,,getting null pointer exception
here
PLACE_URL = "http:///webservices/wish_friend.php?user_id="+userids+"&det="+friendid+"&occ="+ URLEncoder.encode(realtions);
Just check before accessing intent data
if( getIntent().getExtras() != null){
// intent has data
Intent intent=getIntent();
userids= intent.getStringExtra("userid");
...
}
else
{
//probably you are from C->B after back press
}
In the Android application I'm working on, I have one activity where the user inputs data that is saved using SharedPreferences, and is used for certain calculations on the main activity. An issue I'm having is that after saving the data, the changes do not actually take effect until after the application is restarted. Is there a way I can make it so the variables associated with these SharedPreferences are updated before restarting?
Here is where I save the data in a separate activity.
saveBn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
weightString = weightText.getText().toString();
ageString = ageText.getText().toString();
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putString("savedWeight", weightString).commit();
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putString("savedAge", ageString).commit();
//Intent i = new Intent("com.williammiller.capstonelapv2.MainActivity");
//startActivity(i);
finish();
}
});
And here is where I'm checking in the main activity to see what they are
String age = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getString("savedAge", "25");
String weight = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getString("savedWeight", "200");
startBn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "weight = " + weightInt + " age = " + ageInt, Toast.LENGTH_LONG).show();
}
});
You can use a BroadcastReceiver to achieve that. Do as following:
Register a BroadcastReceiver in your Main Activity:
public static final String UPDATE_ACTION = "yourpackage.update";
public static final String EXTRA_KEY_AGE = "key_age";
public static final String EXTRA_KEY_WEIGHT = "key_weight";
private BroadcastReceiver mReceiver;
// In the onCreate() method
mReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(UPDATE_ACTION)){
// Here you get the update data from another activity
String age = intent.getStringExtra(EXTRA_KEY_AGE);
String weight = intent.getStringExtra(EXTRA_KEY_WEIGHT);
}
}
};
registerReceiver(receiver, new IntentFilter(UPDATE_ACTION ));
// Add the following code to onDestroy() method
unregisterReceiver(mReceiver);
Send a broadcast in your "separate activity":
public void onClick(View v) {
weightString = weightText.getText().toString();
ageString = ageText.getText().toString();
Intent intent = new Intent(MainActivity.UPDATE_ACTION );
intent.putExtra(MainActivity.EXTRA_KEY_AGE, ageString);
intent.putExtra(MainActivity.EXTRA_KEY_WEIGHT, weightString );
sendBroadcast(intent);
}
Update: Change part of the code to unregister the BroadcastReceiver when activity is destroyed.
I have an application with two activies. First one is reading serial data from arduino using asynctask. When button is clicked on first activity it should start second activity. But when I click that button it's going to android launcher everytime. Meanwhile second activity also opened in background.
I don't understand why android launcher is opening but not showing second activity on screen.
Any suggestions? Thanks.
private class AdkReadTask extends AsyncTask<Void, String, Void> {
public void pause() {
degisken = false;
}
#Override
protected Void doInBackground(Void... arg0) {
while (degisken) {
publishProgress(mAdkManager.readSerial());
SystemClock.sleep(50);
}
return null;
}
protected void onProgressUpdate(String... progress) {
kapak2 = (int) progress[0].charAt(2);
kapak1 = (int) progress[0].charAt(1);
limit = (int) progress[0].charAt(0);
tx5.setText("kapak1 : " + (int) progress[0].charAt(1)
+ " kapak2 : " + (int) progress[0].charAt(2) + " limit : "
+ (int) progress[0].charAt(0));
}
}
public void butonClick(View v) {
Intent intent = new Intent(UDOOBlinkLEDActivity.this,
shortcuts.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("dil", dil);
startActivity(intent);
}
Change this.
Intent intent = new Intent(UDOOBlinkLEDActivity.this,
shortcuts.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// startActivity(intent); remove this line
intent.putExtra("dil", dil);
startActivity(intent);
Because twice you are calling startActivity(intent); and after that you are sending data and again startActivity. So problem occurs.
I am using IntentService to download 200 large JPGs from a list. While this is loading, the user can skip through the not-loaded JPGs and load JPG #156 for example, but after it is loaded, it should continue loading the rest. So it's like a Lazy Loader... but it continues when it's idle.
I previously used onHandleIntent and put a loop from #1 to #200... which obviously doesn't work when I try to send another IntentService call for JPG #156. So the call to #156 only happens after onHandleIntent is done with #200.
I then changed it so onHandleIntent reorders request #156 to be at the top of the list, then requests the top of the list (and downloads the JPG), then removes it from the list. It then calls the IntentService again, which sounds rather risky from a recursive/stack overflow kinda way. It works sometimes and I can see file #156 being put first... sometimes.
Is there a better way to do this? A way I could think of would be to run it all through a database.
EDIT: This is what I have come up with:
code
public class PBQDownloader extends IntentService {
int currentWeight = 0;
PriorityBlockingQueue<WeightedAsset> pbQueue = new PriorityBlockingQueue<WeightedAsset>(100, new CompareWeightedAsset());
public PBQDownloader() {
super("PBQDownloader");
}
public PBQDownloader(String name) {
super(name);
}
#Override
protected void onHandleIntent(Intent intent) {
String downloadUrl = "-NULL-";
Bundle extras = intent.getExtras();
if (extras!=null) {
downloadUrl = extras.getString("url");
Log.d("onHandleIntent 1.1", "asked to download: " + downloadUrl);
} else {
Log.d("onHandleIntent 1.2", "no URL sent so let's start queueing everything");
int MAX = 10;
for (int i = 1; i <= MAX; i++) {
// should read URLs from list
WeightedAsset waToAdd = new WeightedAsset("url: " + i, MAX - i);
if (pbQueue.contains(waToAdd)) {
Log.d("onStartCommand 1", downloadUrl + " already exists, so we are removing it and adding it back with a new priority");
pbQueue.remove(waToAdd);
}
pbQueue.put(waToAdd);
}
currentWeight = MAX + 1;
}
while (!pbQueue.isEmpty()) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
WeightedAsset waToProcess = pbQueue.poll();
Log.d("onHandleIntent 2 DOWNLOADED", waToProcess.url);
}
Log.d("onHandleIntent 99", "finished all IntentService calls");
}
#Override
public int onStartCommand(Intent intent, int a, int b) {
super.onStartCommand(intent, a, b);
currentWeight++;
String downloadUrl = "-NULL-";
Bundle extras = intent.getExtras();
if (extras!=null) downloadUrl = extras.getString("url");
Log.d("onStartCommand 0", "download: " + downloadUrl + " with current weight: " + currentWeight);
WeightedAsset waToAdd = new WeightedAsset(downloadUrl, currentWeight);
if (pbQueue.contains(waToAdd)) {
Log.d("onStartCommand 1", downloadUrl + " already exists, so we are removing it and adding it back with a new priority");
pbQueue.remove(waToAdd);
}
pbQueue.put(waToAdd);
return 0;
}
private class CompareWeightedAsset implements Comparator<WeightedAsset> {
#Override
public int compare(WeightedAsset a, WeightedAsset b) {
if (a.weight < b.weight) return 1;
if (a.weight > b.weight) return -1;
return 0;
}
}
private class WeightedAsset {
String url;
int weight;
public WeightedAsset(String u, int w) {
url = u;
weight = w;
}
}
}
code
Then I have this Activity:
code
public class HelloPBQ extends Activity {
int sCount = 10;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button tv01 = (Button) findViewById(R.id.tv01);
Button tv02 = (Button) findViewById(R.id.tv02);
Button tv03 = (Button) findViewById(R.id.tv03);
tv01.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
doPBQ();
}
});
tv02.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
doInitPBQ();
}
});
tv03.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
sCount = 0;
}
});
}
private void doInitPBQ() {
Intent intent = new Intent(getApplicationContext(), PBQDownloader.class);
//intent.putExtra("url", "url: " + sCount);
startService(intent);
}
private void doPBQ() {
sCount++;
Intent intent = new Intent(getApplicationContext(), PBQDownloader.class);
intent.putExtra("url", "url: " + sCount);
startService(intent);
}
}
code
Now the messy bit is that I have to keep an ever-increasing counter that runs the risk of going out of int bounds (WeightedAsset.weight) - is there a way to programmatically add to the queue and have it automatically be the head of the queue? I tried to replace WeightedAsset with a String, but it didn't poll() as I wanted, as a FIFO instead of a LIFO stack.
Here's how I'd try it first:
Step #1: Have the IntentService hold onto a PriorityBlockingQueue.
Step #2: Have onHandleIntent() iterate over the PriorityBlockingQueue, downloading each file in turn as it gets popped off the queue.
Step #3: Have onStartCommand() see if the command is the "kick off all downloads" command (in which case, chain to the superclass). If, instead, it's the "prioritize this download" command, re-prioritize that entry in the PriorityBlockingQueue, so it'll be picked up next by onHandleIntent() when the current download is finishing.