I have a progress bar simply designed and placed in MainActivity.
I have second activity to set max value of ProgressBar
My question is; how can use public void onActivityResult(int requestCode, int resultCode, Intent data)'s returned value for ProgressBar's setMax() method?
package com.example.example;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends Activity {
final int request_Code = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*I want to use value cames from onActivityResult() for setMax()
instead of default entered value -> 100 */
ProgressBar calorieBar = (ProgressBar) findViewById(R.id.progress1);
calorieBar.setMax(100);
calorieBar.setProgress(70);
//Go to another Activity and start
Button newPlan = (Button) findViewById(R.id.newPlanBTN);
newPlan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent("com.hakkikonu.dailycalorie.NEWPLAN");//new_plan activity
startActivityForResult(i, 1);
onResume();
}
});
}//end of onCreate
//Sets Calorie value Comes from NewPlan.java and makes it Toast to show user
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == request_Code) {
if (resultCode == RESULT_OK) {
Toast.makeText(this,"Adjusted to "+data.getData().toString(),
Toast.LENGTH_LONG).show();
// Do somethings here: get data and convert it to integer
}
}
}
}
NewPlan.Java
package com.hakkikonu.dailycalorie;
import com.hakkikonu.dailycalorie.R.layout;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.TextView;
public class NewPlan extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_plan);
final TextView seekBarValue = (TextView)findViewById(R.id.seekBarValue);
//Plan Button Click Listener
final Button setPlanButton = (Button)findViewById(R.id.setPlanBTN);
setPlanButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
setPlanButton.setBackgroundColor(Color.YELLOW);
Intent calorieVal = new Intent();
//---set the data to pass back---
calorieVal.setData(Uri.parse(
seekBarValue.getText().toString()));
setResult(RESULT_OK, calorieVal);
//---closes the activity---
finish();
}
});//end SetPlan Button Listener
SeekBar seekBar = (SeekBar)findViewById(R.id.seekBar);
seekBar.setProgress(0); //initial value of seekBar
seekBar.incrementProgressBy(50); //increment step
seekBar.setMax(5000); //maximum possible calory for a day.
//seekBar Listener
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
//text view # top of the seekBar
progress = progress / 50;
progress = progress * 50;
if(progress == 0){
seekBarValue.setText(String.valueOf(progress)+" Calorie");
}
else{
seekBarValue.setText(String.valueOf(progress)+" Calories");
}
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
//Don't delete
}
#Override
public void onStopTrackingTouch(SeekBar arg0) {
// Don't delete
}
});
}
}
Assuming your second Activity puts an int as its extra, with a key of "YOUR_KEY" in its result Intent, just simply set the progress bar's max to that int extra:
//Sets Calorie value Comes from NewPlan.java and makes it Toast to show user
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == request_Code) {
if (resultCode == RESULT_OK) {
Toast.makeText(this,"Adjusted to "+data.getData().toString(),
Toast.LENGTH_LONG).show();
((ProgressBar) findViewById(R.id.progress1)).setMax (data.getIntExtra ("YOUR_KEY", 0));
}
}
}
To make things simple (I'd say):
public class NewPlan extends Activity{
private int myProgress = 0;//add this line
Then in the changed listener:
progress = progress / 50;
progress = progress * 50;
myProgress = progress;//add this line
Then to set the data, change to this:
Intent calorieVal = new Intent();
calorieVal.putExtra ("YOUR_KEY", myProgress);
setResult(RESULT_OK, calorieVal);
//---closes the activity---
finish();
This is how you set resulting intent in NEWPLAN Activity:
Intent intent = new Intent();
intent.putExtra("myInt", 12);
setResult(Activity.RESULT_OK, intent);
finish();
And then in MainActivity you fetch that data using:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == yourRequestCode && RESULT_OK) {
int myInt = data.getIntExtra("myInt", 0);
// do more if you wish
}
}
Related
i want use toggle switch by voice commands like switch on and switch off so i got a code for voice recognition from a site but dont know how to trigger my toggle button thru it
The code of voice recognition i used -
package com.authorwjf.talk2me;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
protected static final int REQUEST_OK = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button1).setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
try {
startActivityForResult(i, REQUEST_OK);
} catch (Exception e) {
Toast.makeText(this, "Error initializing speech to text engine.", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==REQUEST_OK && resultCode==RESULT_OK) {
ArrayList<String> thingsYouSaid = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
((TextView)findViewById(R.id.text1)).setText(thingsYouSaid.get(0));
}
}
}
your array thingsYouSaid have all possible string array you have . for example if I say hello it will have like [hello,aloe,hallo,no] so what you have to do is you can match your string switch off to result string array and if it is match with like "switch off" than change value of your switch from on to off likewise;
if (requestCode==REQUEST_OK && resultCode==RESULT_OK) {
ArrayList<String> thingsYouSaid = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
for(String value : thingsYouSaid.get(0)){
if(value.equalsignorecase("switch off")){
// change value for switch to off
break;
}
else if(value.equalsignorecase("switch on")){
// change value for switch to on
break;
}
}
i am using voice recognizer in my app. but i want a single result from the voice recognizer without the "[" and "]" in the beginning and the end of the result provided by the voice recognizer.
at present i have a code which gives me a single result but it give "[" and "]" in the front and in the end of the result which i obtain.
please check my code make the possible correction and modifications and give a appropiate answer i am very new to android.
code : MainActivity.java
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private static final int RECOGNIZER_EXAMPLE = 1001;
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.text_result);
//set up button listner
Button startButton = (Button) findViewById(R.id.trigger);
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent =
new Intent (RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,"SAY A WORD OR PHRASE\nAND IT WILL BE SHOWN AS TEXT");
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
startActivityForResult(intent,RECOGNIZER_EXAMPLE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//use a switch statament for more than one request code check
if(requestCode==RECOGNIZER_EXAMPLE && resultCode==RESULT_OK) {
//RETURNED DATA IS A LIST OF MATCHES TO THE SPEECH IPUT
ArrayList<String> result =
data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
tv.setText(result.toString());
}
super.onActivityResult(requestCode, resultCode, data);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//use a switch statament for more than one request code check
if(requestCode==RECOGNIZER_EXAMPLE && resultCode==RESULT_OK) {
//RETURNED DATA IS A LIST OF MATCHES TO THE SPEECH IPUT
ArrayList<String> result =
data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
// result here is array list , we need any element to be viewed in textview
tv.setText(result.get(0).toString());
}
super.onActivityResult(requestCode, resultCode, data);
}
So the change we made
tv.setText(result.toString());
To
tv.setText(result.get(0).toString());
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private static final int RECOGNIZER_EXAMPLE = 1001;
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.text_result);
//set up button listner
Button startButton = (Button) findViewById(R.id.trigger);
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent =
new Intent (RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,"SAY A WORD OR PHRASE\nAND IT WILL BE SHOWN AS TEXT");
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
startActivityForResult(intent,RECOGNIZER_EXAMPLE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//use a switch statament for more than one request code check
if(requestCode==RECOGNIZER_EXAMPLE && resultCode==RESULT_OK) {
//RETURNED DATA IS A LIST OF MATCHES TO THE SPEECH IPUT
ArrayList<String> result =
data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
tv.setText(result.get(0).toString());
}
super.onActivityResult(requestCode, resultCode, data);
}
}
This question already has answers here:
How to start new activity on button click
(28 answers)
Closed 8 years ago.
I am trying to write a code in Android to pass a value from a button click to another class. I am getting 0 value in the Log and i am not finding any technique to send the proper value.
Please go through my below code :
Java Code:
MainActivity.java
package com.example.mybuttonvalue;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
public class MainActivity extends Activity
{
Activity activity;
Context cont;
public static int mysum;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button)findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this,MySum.class);
intent.putExtra("key",5);
startActivityForResult(intent,2);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
}
} }
MySum.java
package com.example.mybuttonvalue;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
public class MySum extends Activity
{
Activity activity;
Context context;
int value = getIntent().getIntExtra("key",0); // 0 is default vlaue
public MySum(Activity activity,Context cont)
{
this.activity = activity;
this.context = cont;
}
public void check(final int x)
{
final Dialog dia = new Dialog(context);
dia.requestWindowFeature(dia.getWindow().FEATURE_NO_TITLE);
dia.setContentView(R.layout.check);
Button btn = (Button) dia.findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
int no = 12+x;
myvalue(no);
Intent intent= getIntent();
intent.putExtra("result",x);
setResult(2,intent);
dia.dismiss();
}
});
dia.show();
}
public String myvalue(int x)
{
return String.valueOf(x);
}
}
Log Report
05-18 23:04:29.603: D/My Value :(10375): 0
This is the above code , how can i get 17 in the Log. I should get the result from MySum class to MainActivity class.
Please let me know , suggest me some good solution.
You are instantiating a Activity class public class MySum extends Activity which is wrong
MySum my = new MySum(MainActivity.this,MainActivity.this);
Remove the constructor and the above code.
You need to use intent to pass values between activities. To get value back in MainActivity use startActivityForResult and override onActivityResult and get the value using intent.
Example:
In MainActivity.java
Intent intent = new Intent(MainActivity.this,MySum.class);
intent.putExtra("key",5);
startActivityForResult(intent,2);
Then override onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
//get data using intent
int result = data.getIntextra("result",0);
}
}
In MySum.java
int value = getIntent().getIntExtra("key",0); // 0 is default vlaue
Do operation on value
Then to return result
Intent intent= getIntent();
intent.putExtra("result",x);
setResult(2,intent);
Edit:
public class MySum extends Activity
{
#Override
protectes void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mysumlayout); //set layout for mysum
int value = getIntent().getIntExtra("key",0);
check(value);
}
public void check(int x)
{
final Dialog dia = new Dialog(MySum.this);
dia.requestWindowFeature(dia.getWindow().FEATURE_NO_TITLE);
dia.setContentView(R.layout.check);
Button btn = (Button) dia.findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
int no = 12+x;
dia.dismiss();
Intent intent= getIntent();
intent.putExtra("result",no);
setResult(2,intent);
finish();
}
});
dia.show();
}
}
Note:
Apart from the above code which is just an example you need not have a Activity at all. All you do is some calculation on a int value which does not require a ui. It could be a normal java class which does just some operation without dialog or any other ui stuff.
I'm trying to use a barcode scanner and then take that input and use in another activity to open with a url. I've been able to get the data to return, just not in another activity and haven't seen any projects exactly like this. I'm not sure if it has to do with intent or how I'm calling the string. The webview in the second java works but doesn't take the string. Thanks for the help!
Scanner.java (which works okay)
package com.pangolin.rollin.ts;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class Scanner extends Activity {
TextView tvStatus;
TextView tvResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scanner);
Button websku = (Button) findViewById(R.id.btnsku);
websku.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent myintent = new Intent(Scanner.this, Websku.class);
startActivity(myintent);
}
});
tvStatus = (TextView) findViewById(R.id.tvStatus);
tvResult = (TextView) findViewById(R.id.tvResult);
Button scanBtn = (Button) findViewById(R.id.btnScan);
// in some trigger function e.g. button press within your code you
// should add:
scanBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
try {
Intent intent = new Intent(
"com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE,PRODUCT_MODE");
startActivityForResult(intent, 0);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "ERROR:" + e, Toast.LENGTH_LONG)
.show();
}
}
});
}
// In the same activity you’ll need the following to retrieve the results:
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
tvStatus.setText(intent.getStringExtra("SCAN_RESULT_FORMAT"));
tvResult.setText(intent.getStringExtra("SCAN_RESULT"));
} else if (resultCode == RESULT_CANCELED) {
tvStatus.setText("Press a button to start a scan.");
tvResult.setText("Scan cancelled.");
}
}
}
}
And websku.java (doesn't work, supposed to take results from previous activity.
package com.pangolin.rollin.ts;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class Websku extends Activity {
final Activity activity = this;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String sku = intent.getStringExtra("SCAN_RESULT");
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.activity_websku);
WebView webView = (WebView) findViewById(R.id.webview_sku);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
activity.setTitle("Loading...");
activity.setProgress(progress * 100);
if (progress == 100)
activity.setTitle(R.string.title_activity_websku);
}
});
webView.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
// Handle the error
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
webView.loadUrl("http://m.radioshack.com/radioshack/catalog/searchList.do?categoryId=&keyword="+sku);
};
}
You don't set any extra to Websku intent:
websku.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent myintent = new Intent(Scanner.this, Websku.class);
startActivity(myintent);
}
});
Should be:
websku.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent myintent = new Intent(Scanner.this, Websku.class);
myintent.putExtra("somename", somevalue);
startActivity(myintent);
}
});
You don't set the extras for the websku Activity. Save the intent returned from the scanner:
private Intent mWebskuIntent;
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
mWebskuIntent = intent;
// more of your code
Then when you start the websku Activity make a copy of the saved intent which will copy also the extras returned from the scanner:
Intent myintent = new Intent(mWebskuIntent);
myintent.setClass(Scanner.this, Websku.class);
startActivity(myintent);
You might want to check for mWebskuIntent being null as well.
How can i open Android device contacts list at button click event.
Try this code..
yourButton.setOnClickListener(new YouButtonEvent());
class YouButtonEventimplements OnClickListener{
#Override
public void onClick(View v) {
Intent it= new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
startActivityForResult(it, PICK_CONTACT);
}
}
Declare Some variables. Create a method & handle the events.
private static final int CONTACT_PICKER_RESULT = 1001;
private static final String DEBUG_TAG = "Contact List";
private static final int RESULT_OK = -1;
// a method to open your contact list
private void openContactList() {
Intent it = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
startActivityForResult(it, CONTACT_PICKER_RESULT);
}
// handle after selecting a contact from the list
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case CONTACT_PICKER_RESULT:
// handle contact results
Log.w(DEBUG_TAG, "Warning: activity result is ok!");
break;
}
} else {
// gracefully handle failure
Log.w(DEBUG_TAG, "Warning: activity result not ok");
}
}
You can use this source code as a reference:
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Test1Activity extends Activity {
private static final int PICK_CONTACT_REQUEST = 1;
private static final int PICK_CONTACT = 0;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button pickContact = (Button) findViewById(R.id.button1);
pickContact.setOnClickListener(new OnClickListener()
{
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_INSERT_OR_EDIT);
i.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
startActivity(i);
}
});
}
}
if u want to pick contact from your device then use this code.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openContect();
dialog.dismiss();
}
and openContact() is:
private void openContect() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, REQUEST_SELECT_CONTACT);
}
}
and in your onActivityResult() use this:
if (requestCode==REQUEST_SELECT_CONTACT && resultCode == RESULT_OK && null != data){
Uri contactUri = data.getData();
//do what you want...
}