I'm frustrated as to how I can get the function to work properly.
I've been researching and looking around about Intents.
At first I thought I got it right but I was wrong, some overview on what I mean.
I have made an app with 6 buttons, all of which that open different applications.
Clock, 2. Calendar, 3. Browser, 4. Messaging, 5. Phone, and 6. Contacts.
This is my onClick method for launching the contacts application.
// Contacts Launch
Button contacts_launch = (Button) findViewById(R.id.contacts_launch);
contacts_launch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent_contacts = new Intent(Intent.ACTION_MAIN);
intent_contacts.addCategory(Intent.CATEGORY_LAUNCHER);
startActivity(intent_contacts);
}
});
The onClick Intent method is the same for all my buttons, just the intent name has been changed according to the applications name, like messaging is intent_message.
When launching the application, and when I tapped the button. It prompted me with a window where I could select the application. And it ran the app every time I selected the button.
But when I select another application, it launches the contacts app? And doesn't let me choose it like before. How can I fix this? I'm pretty sure I'm using the intent function wrong.
Thanks for your time.
Please check code again, that was my modified one that didn't work which was the one with only one intent method. I added the code that I used at first where it let me choose. That's the one with the intent and category. (The one you can see now)
if you dont want to select the Activity over and over again (like when using createChooser) try this:
public class Chooser extends Activity implements OnClickListener {
private static final int NUM = 6;
private static final CharSequence DEFAULT = "click for select the app, long click to clear it";
private Intent[] mIntents = new Intent[NUM];
private LinearLayout mLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLayout = new LinearLayout(this);
mLayout.setOrientation(LinearLayout.VERTICAL);
for (int i = 0; i < NUM; i++) {
Button b = new Button(this);
b.setTag(i);
b.setText(DEFAULT);
b.setOnClickListener(this);
registerForContextMenu(b);
mLayout.addView(b);
}
setContentView(mLayout);
}
private CharSequence getName(Intent intent) {
PackageManager mgr = getPackageManager();
ResolveInfo info = mgr.resolveActivity(intent, 0);
if (info != null) {
return info.loadLabel(mgr);
}
return intent.getComponent().getShortClassName();
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
int itemId = (Integer) v.getTag();
if (mIntents[itemId] != null) {
menu.add(Menu.NONE, itemId, Menu.NONE, "Clear");
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
int i = item.getItemId();
Button b = (Button) mLayout.getChildAt(i);
b.setText(DEFAULT);
mIntents[i] = null;
return super.onContextItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Button b = (Button) mLayout.getChildAt(requestCode);
b.setText(getName(data));
mIntents[requestCode] = data;
startActivity(data);
}
}
#Override
public void onClick(View v) {
int i = (Integer) v.getTag();
if (mIntents[i] == null) {
Intent intent = new Intent(Intent.ACTION_PICK_ACTIVITY);
Intent filter = new Intent(Intent.ACTION_MAIN);
filter.addCategory(Intent.CATEGORY_LAUNCHER);
intent.putExtra(Intent.EXTRA_INTENT, filter);
startActivityForResult(intent, i);
} else {
startActivity(mIntents[i]);
}
}
}
Hi Use the below Code to open contacts:
#SuppressWarnings("deprecation")
Intent intent = new Intent(Intent.ACTION_PICK, People.CONTENT_URI);
startActivity(intent);
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.setData(Uri.parse("sms:"));
sendIntent.putExtra("sms_body", urlToShare);
startActivity(sendIntent);
This is a sample code to open message application or hangout. You can do like this for others also.
Related
i am trying to pass values of filtered chips that a user has selected in order to retrieve only the required shops he want in that particular criteria.
now i created everything and the data i am getting after finishing from my FilterActivity is being passed into my HomeActivity. but this data is not being 'read' or 'accepted' inside my query since it doesn't produce the correct output. When i use a static value inside the query it would work. now i need it to be a changing value depending on what the use has selected.
This is inside my HomeActivity that opens the Filter Activity:
filterBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(HomeActivity.this,FilterActivity.class);
startActivityForResult(intent,101);
}
});
this is my FilterActivity with a few examples:
private Chip rate2,rate3,rate4;
private ArrayList<String> selectedChipData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_filter);
rate2 = findViewById(R.id.chip_Rate_2);
selectedChipData = new ArrayList<>();
CompoundButton.OnCheckedChangeListener checkedChangeListener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if(isChecked){
selectedChipData.add(compoundButton.getText().toString().trim());
}else{
selectedChipData.remove(compoundButton.getText().toString().trim());
}
}
};
rate2.setOnCheckedChangeListener(checkedChangeListener);
}
and this is the button the user clicks when he wants to apply one of the filter options:
filter_reset = findViewById(R.id.filter_reset);
filter_reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent resultIntent = new Intent();
resultIntent.putExtra("data",selectedChipData.toString().trim());
setResult(101,resultIntent);
finish();
}
});
now in my HomeActivity i created the onActivityResult:
String Data;
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==101){
Data = data.getStringExtra("data");
Log.d("TAG", data.getStringExtra("data"));
Query q = firebaseFirestore.collection("Shops").whereEqualTo("location",Data);
}
}
Query q = firebaseFirestore.collection("Shops").whereEqualTo("location",Data);
// this is my query and how i am trying to pass the matched users selected chip to the location of the Shops table.
What am i missing or doing wrong inside my query and how to fix it? can someone advise?
Did by any chance you forget to tell intent to go back to Home Page
filter_reset = findViewById(R.id.filter_reset);
filter_reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent resultIntent = new Intent(FilterActivity.this, MainActivity.class);
// Changed the above Intent Paras
resultIntent.putExtra("data",selectedChipData.toString().trim());
setResult(101,resultIntent);
finish();
}
});
i found the problem, it wasn't matching with my database because the value is an array and has [] in the result. if i put the [] in my database it works fine.
The codes are messy at this point since I've been going back and forth so much. Every time user clicks the yes/no button I want the results of counts the button has been clicked to display in another activity. I also want to reset the number of clicks from the second activity as well. All that's needed in the first activity is the question and the yes/no button. Is this possible? Thanks in advance.
public class MainActivity extends AppCompatActivity {
private static final String TAG = "SurveyActivity";
private static final String YES_INDEX = "yes votes";
private static final String NO_INDEX = "no votes";
Button mYesButton;
Button mNoButton;
Button mResetButton;
TextView mSurveyQuestion;
private int yesVoteCount = 0;
private int noVoteCount = 0;
private int resetVotes = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Use res ID to retrieve inflated objects and assign to variables
mYesButton = findViewById(R.id.yes_button);
mNoButton = findViewById(R.id.no_button);
mResetButton = findViewById(R.id.reset_button);
mSurveyQuestion = findViewById(R.id.survey_question);
mYesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addVote();
}
});
mNoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addVote();
}
});
// Resetting vote count
mResetButton.setOnClickListener(new View.OnClickListener() {
#Override
***Should this supposed to be in the second activity?
}
});
}
private void addVote() {
if (mYesButton.isPressed()) {
yesVoteCount++;
} else if (mNoButton.isPressed()) {
noVoteCount++;
}
}
In your main activity
btnShowResut.setOnClickListener(new View.OnClickListener() {
#Override
// Create intent for going to another activity
Intent intent = new Intent(this, AnotherActivity.class);
// Put counts datas to intent
intent.putExtra("yesCountKey", yesVoteCount);
intent.putExtra("noCountKey", noVoteCount);
// NEW : Go to another activity by calling it instead
// REQUEST_CODE is an integer variable
startActivityForResult(intent, REQUEST_CODE);
}
});
In Another activity, you can retrieve datas in onCreate method like this and send action to clear counts of your main activity.
...
onCreate(...){
...
// Retrieve datas from intent
int yesCount = getIntent().getIntExtra("yesCountKey", 0);
int noCount = getIntent().getIntExtra("noCountKey", 0);
mResetButton.setOnClickListener(new View.OnClickListener() {
#Override
// Send a boolean to main activity for clearing votes
Intent intent = new Intent();
intent.putExtra("resetVotes", true);
setResult(RESULT_OK, intent);
// Close second activity
finish();
}
});
}
Finally in the main activity override this method and clear votes
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode == 2000 && resultCode == RESULT_OK){
boolean reset = data.getBooleanExtra("resetVotes", false);
if(reset){
yesVoteCount = 0;
noVoteCount = 0;
}
}
}
As the mentioned above, you can get the counts by using intent extras.
However if you want to reset the counts in in the second activity you might want to start the Activity B as startActivityForResult() see the Android documentation here.
Then when Activity B end you can reset the counts in the call back method onActivityResult().
If you don't want to do it like this the next best way might be to reset the counts onResume() of Activity A so that when you return to the activity you will start with fresh counts. See life cycle documentation here
I have a fragment which is present in Bottom Navigation Activity. The Fragments contain the custom recyclerview. There is a comment button when i press it opens another activity for comments. Below is in the RecyclerView adapter.
viewholder.commentlay.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//commenttofragment.clear();
Intent comment = new Intent(fp, com.fooddoof.fuddict.comment.class);
int id = dusers.get(position).getId();
int comcount = dusers.get(viewholder.getAdapterPosition()).getCommentcount();
comment.putExtra("id",id);
comment.putExtra("ownerid",userid);
comment.putExtra("maincommentposition",position);
comment.putExtra("commentcountonposition", comcount);
fp.startActivityForResult(comment,1);
}
});
In Comment activity after doing some tasks I need to send some values to this fragment. So I Override the OnBackPressed method. I have created a method in Fragment to receive it.
#Override
public void onBackPressed()
{
Bundle args = new Bundle();
args.putInt("maincommentcount",maincommentcount);
args.putInt("maincommentposition", maincommentposition);
FolowersPost f = new FolowersPost();
f.getdatafromcomment(args);
finish();
}
I receive it like below in Fragment.
public void getdatafromcomment(Bundle args)
{
int count = args.getInt("maincommentcount");
int p=args.getInt("maincommentposition",999999999);
Log.e("Shiva","count--->"+count+"p--->"+p);
}
The Values are received but I need to access the arraylist in Fragement which is passed in Adapter for displaying the recyclerView. But I am not able to access it while I am coming back to fragment which is present in the method under OnCreateView. I tried with OnResume to access it but works for some time only. I have declared the Arraylist as global variable also.
You are already using startActivityForResult. now you just need to use onActivityResult.
But you just need to start activity from fragment instead of from adapter.
onClick from fragment:
Intent comment = new Intent(getActivity(), com.fooddoof.fuddict.comment.class);
startActivityForResult(comment, 1);
onBackPressed in your comment activity:
#Override
public void onBackPressed() {
Intent returnIntent = new Intent();
returnIntent.putExtra("maincommentcount",10);
returnIntent.putExtra("maincommentposition",20);
setResult(Activity.RESULT_OK,returnIntent);
finish();
// super.onBackPressed();
}
onActivityResult in fragment:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == Activity.RESULT_OK) {
int mMaincommentcount = data.getIntExtra("maincommentcount", 0);
int mMaincommentposition = data.getIntExtra("maincommentposition", 0);
System.out.println("mMaincommentcount = " + mMaincommentcount + ", mMaincommentposition = " + mMaincommentposition);
}
}
}
I have a MainActivity which has a ListView, when I click the ListView it opens a new activity for that item.
I want to be able to change the information in that item, then when I click back it changes the ListView.
Here's some of the code I have:
MainActivity:
String[] people;
private ListView mListView;
public static ArrayAdapter<String> adapter;
In onCreate(){
people = new String[] {"", "", "", "", "", "", "", ""};
mListView = (ListView) findViewById(R.id.personListView);
adapter = (new ArrayAdapter<String>(this, R.layout.list_item, people);
mListView.setAdapter(adapter);
mListView.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Current item
String person = ((TextView) view).getText().toString();
// Launch new activity based on item
Intent intent = new Intent(getApplicationContext(), SinglePerson.class);
//
intent.putExtra("person", person);
//intent.putExtra("peopleList", people);
intent.putExtra("position", position);
startActivityForResult(intent, 1);
//
}
});
I have this in the class which I thought would get the information from the other activity back but nothing happens:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == 1) {
// Make sure the request was successful
if(resultCode == RESULT_OK){
int listPos = data.getIntExtra("listPosition", 1);
//edit listview value at position
people[listPos] = data.getStringExtra("edittextvalue");
adapter.notifyDataSetChanged();
}
}
}
In the other activity class:
public class SinglePerson extends Activity{
String[] people;
int position;
Intent intent;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
this.setContentView(R.layout.single_person_item_view);
EditText txtPerson = (EditText) findViewById(R.id.person_name);
intent = getIntent();
String person = intent.getStringExtra("person");
//people = intent.getStringArrayExtra("peopleList");
position = intent.getIntExtra("position", 0);
txtPerson.setText(person);
}
private TextWatcher peopleNumberListener = new TextWatcher(){
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
//people[position] = s.toString();
//BillSplit.adapter.notifyDataSetChanged();
intent.putExtra("edittextvalue",s.toString());
intent.putExtra("listPosition", position);
setResult(RESULT_OK, intent);
//finish();
}
};
As per my comment above, if you are pressing the back key then you're not properly finishing the Activity. What you want to do is when you're ready to end the Activity, either in a Button or some other action, then do the following (which it looks like you had already mostly figured out)
...
// you can create a new Intent for the result
Intent newIntent = new Intent();
newintent.putExtra("edittextvalue",s.toString());
newintent.putExtra("listPosition", position);
setResult(RESULT_OK, newintent);
finish();
...
EDIT: In response to those who are posting to override onBackPressed(), this will allow you to intercept the back key when you press it within your Activity and decide how you want to handle it. However, please note the implication of doing this: if this is for the general public, most users will expect the back key to take you some form of "back", but this is not the same as completion or progressing through the normal flow of your app (which you are looking to do by making a selection and then continue where you left off). So while this may accomplish the desired behavior, it's debatable whether this is the correct solution for you.
I would use Singleton if you have more than two activities. If its just two then probably using intent.put. Thanks,
EDIT: onClick is working properly now. The issue was that the button was trying to fire the onClick from the Parent class. now that is fixed. Of course that means a new issue is happening, that is the onActivityResult is never getting called.
So I am not really sure what the hell is going on, when I hit the button nothing happens, nothing in logcat, nothing, as if there is not code, but I am pretty sure this is written correctly, any thoughts?
public class myClass extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.store_selector);
Button getStore = (Button)findViewById(R.id.getStore);
getStore.setOnClickListener(buttonGetStoreOnClickListener);
}
Button.OnClickListener buttonGetStoreOnClickListener
= new Button.OnClickListener(){
public void onClick(View arg0) {
Intent intent = new Intent("com.blah.Blah.client.android.SCAN");
intent.setPackage("com.blah.Blah");
intent.putExtra("com.blah.Blah.client.android.SCAN.SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
};
};
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
if (requestCode == 0)
{
if (resultCode == RESULT_OK)
{
String contents = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
Log.i("debug tag", "contents: "+contents+" format: "+format);
Intent myIntent = new Intent(this, Ads.class);
myIntent.putExtra("key", contents);
startActivity(myIntent);
setContentView(R.layout.activity_ads);
// Handle successful scan
}
else if (resultCode == RESULT_CANCELED)
{
// Handle cancel
Log.i("xZing", "Cancelled");
}
}
}
};
This is the class you need to import:
import android.view.View.OnClickListener;
And this is the method you should have:
OnClickListener onButtonListener = new OnClickListener() {
#Override
public void onClick(View v) {
// Your code here
}
};
Test it and let me know if it worked.
Regards
Are you sure you got the right button with Button getStore = (Button)findViewById(R.id.getStore); ?
If yes, then it can be something that sometimes happens to me sometimes.
When this happens, my logcat doesn't show anything. What I do to solve this, is to open the Devices view (Window, show view, other, Android, Devices) and select my device. Then when I look at the logcat again, everything's there.