Whenever the user clicks the "phone icon" and sms icon an intend Dials a number or Sends an SMS. I don't know how to code my OnClickListener so that the two icons in the list view respond to the click event
MainActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ArrayList<Student> students = new ArrayList<Student>();
ListView studentListView = (ListView) findViewById(R.id.list);
StudentAdapter adapter = new StudentAdapter(this, R.layout.item_list, students);
studentListView.setAdapter(adapter);
studentListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Student student = students.get(position);
String url = student.getStudentNumber();
Student student = students.get(position);
String url = student.getStudentNumber();
Intent smsIntent = new Intent(android.content.Intent.ACTION_VIEW);
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.putExtra("address", url);
smsIntent.putExtra("sms_body", "your desired message");
startActivity(smsIntent);
}
}
});
}
}
this Sms intent works fine when I click anywhere of the item of my ListView but
let's say there is a with "sms icon" and R.id.smsButton in each item and I only want that to respond to the click event and start the intent, not any other Views in the Item of my CustomListView.
`
write click listeners in getView() method of adapter class itself
public View getView(int pos, View convertView, ViewGroup parent){
...
Button button = (Button) row.findViewById(R.id.button);
button.setOnClickListener(new OnClickListener(){
public void onClick(View v){
//do something
}
});
...
return row;
}
Related
My problem is that my code does not react accordingly whenever an user selects an item from an AutoCompleteTextView.
flag is a variable which is set to a value whenever one item from each AutoCompleteTextView has been selected. If it's set to 1, then it means it's right and it should proceed to main activity. Otherwise, a toast is displayed on click of button whose onClick calls the method callMainActivity.
There are no errors. Gradle build is successful, but clicking on that button (mentioned above) does nothing at all.
Code:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.Arrays;
import java.util.List;
public class Location extends AppCompatActivity {
private static int flag=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
int city = android.R.layout.simple_dropdown_item_1line;
int area = android.R.layout.simple_dropdown_item_1line;
int store = android.R.layout.simple_dropdown_item_1line;
String []city_array = getResources().getStringArray(R.array.City);
String []area_array= getResources().getStringArray(R.array.Area);
String []store_array= getResources().getStringArray(R.array.Store);
List<String> city_list= Arrays.asList(city_array);
List<String> area_list= Arrays.asList(area_array);
List<String> store_list= Arrays.asList(store_array);
ArrayAdapter<String> adapter_city = new ArrayAdapter(this,city, city_list);
ArrayAdapter<String> adapter_area = new ArrayAdapter(this, area, area_list);
ArrayAdapter<String> adapter_store = new ArrayAdapter(this, store, store_list);
final AutoCompleteTextView autocompleteView_city =
(AutoCompleteTextView) findViewById(R.id.City);
final AutoCompleteTextView autocompleteView_area =
(AutoCompleteTextView) findViewById(R.id.Area);
final AutoCompleteTextView autocompleteView_store =
(AutoCompleteTextView) findViewById(R.id.Store);
autocompleteView_area.setAdapter(adapter_area);
autocompleteView_city.setAdapter(adapter_city);
autocompleteView_store.setAdapter(adapter_store);
autocompleteView_area.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View arg0) {
autocompleteView_area.showDropDown();
if(autocompleteView_area.getListSelection()!= ListView.INVALID_POSITION)
flag=1;
else
flag=0;
}
});
autocompleteView_city.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View arg0) {
autocompleteView_city.showDropDown();
if(autocompleteView_area.getListSelection()!= ListView.INVALID_POSITION)
flag=1;
else
flag=0;
}
});
autocompleteView_store.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View arg0) {
autocompleteView_store.showDropDown();
if(autocompleteView_area.getListSelection()!= ListView.INVALID_POSITION)
flag=1;
else
flag=0;
}
});
//This is the newly updated part
autocompleteView_area.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick (AdapterView<?> parent, View view, int position, long id) {
//... your stuff
if(autocompleteView_area.getListSelection()>0) {
flag = 1;
System.out.println(flag + "flag at area");
}else
flag=0;
}
});
}
public void callMainActivity(View view){
if(flag==1) {
Intent in = new Intent(getBaseContext(), MainActivity.class);
startActivity(in);
}
else
Toast.makeText(getBaseContext(),"Please select all fields properly",Toast.LENGTH_LONG);
}
}
The reason you are not seeing the Toast or changing activities, is because you are never calling callMainActivity(View view) in your code. Add this line to the end of all your OnClickListeners: callMainActivity(arg0) -- if this does not work, put some log statements in your OnClickListeners to check if they are triggering or not.
Also, if you want to trigger the call when an item from your AutoCompleteTextView result list is selected, you should use an AdapterView.OnItemClickedListener instead. This will notify you when an item is selected from the AutoCompleteTextView list, or when nothing is selected and then you can react accordingly.
I got problem when trying to get checked item from listView through predefined xml layout simple_list_item_single_choice and select item then set text of a TextView that is in another activity.
This is my showMyUI method that call from MainActivity on click of TextView
dateRange.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(MainActivity.this, "Range clicked",Toast.LENGTH_SHORT).show();
DateRangeClass day=new DateRangeClass(MainActivity.this,dayRangeSelected);
day.showMyUI();
overridePendingTransition(R.anim.right_to_left, R.anim.left_to_right);
}
});
And my DateRangeClass is
package tutorial.projecttwofilter;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class DateRangeClass {
Context context;
LinearLayout backButton;
ListView rangeList;
TextView rangeText;
String[] dateRangeData= new String[]{"Next 7 Days", "Next 14 Days", "Next 30 Days"};
public DateRangeClass(Context context,TextView rangeText) {
this.context = context;
this.rangeText=rangeText;
}
public void showMyUI(){
((Activity)context).setContentView(R.layout.daterange);
backButton= (LinearLayout) ((Activity)context).findViewById(R.id.backButton);
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((Activity) context).finish();
((Activity) context).overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);
}
});
rangeList= (ListView) ((Activity)context).findViewById(R.id.dateRangeList);
ArrayAdapter<String> adapter= new ArrayAdapter<>(context, android.R.layout.simple_list_item_single_choice, dateRangeData);
rangeList.setAdapter(adapter);
rangeList.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
rangeList.setItemChecked(position, true);
if(rangeList.isItemChecked(position))
Toast.makeText(context, "Checked item is"+rangeList.getCheckedItemPosition(), Toast.LENGTH_SHORT).show();
rangeText.setText("You new Change "+rangeList.getCheckedItemPosition());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(context, "Nothing selected", Toast.LENGTH_SHORT).show();
}
});
}
}
Create DateRangeClass as an activity not as normal class and pass the information using bundle. As i can see you are passing textview instead of that you can pass text as string and can show in second activity.
To transfer data
String textToBesend = "Text from textview";
Intent i = new Intent(this, DateRangeActivity.class);
i.putExtra("text", textToBesend);
startActivity(i);
and to recieve data in DateRangeActivity write this in oncreate method.
Intent intent = getIntent();
String textPassedFromFirstActivity = intent.getExtras().getString("text");
You can refer below tutorial for your purpose hope it helps.
passing data to activity from listview
You have not started your activity.
Use startActivity and putIntent method on button click and in your second activity use getIntent method to display the text.
I made an Activity for searching people that also shows history of recent research.
If I long click on an item of the history it asks me if I want to delete it. If I press "Yes" it deletes the list item.
So, I write something and click to "Search" button. This brings me in another Activity with results. Here I click on result so it stores the person info and brings me in the person page.
When I come back I don't see the new person in the history.
So I overwritten onResume() but it still not work and now I cannot delete items from the history list.
Here the code:
package com.lpsmt.proffinder;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.lpsmt.R;
public class HomeActivity extends Activity
{
protected Db db = null;
protected List<ProfBean> historyProfs = null;
protected ProfListItemAdapter listAdapter = null;
protected ListView listView = null;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.db = new Db(this);
this.setContentView(R.layout.prof_finder_home);
this.historyProfs = this.db.getHistory(-1); // -1 means with no limits
this.listAdapter = new ProfListItemAdapter(HomeActivity.this, R.id.prof_finder_history_list_view, this.historyProfs);
this.listView = (ListView) this.findViewById(R.id.prof_finder_history_list_view);
listView.setAdapter(this.listAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(HomeActivity.this, ProfPageActivity.class);
Bundle bundle = new Bundle();
bundle.putString("profId", HomeActivity.this.historyProfs.get(position).getProfId());
intent.putExtras(bundle);
HomeActivity.this.startActivity(intent);
}
});
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id)
{
Resources resources = HomeActivity.this.getResources();
String title = resources.getString(R.string.prof_finder_history_delete_title);
String message = resources.getString(R.string.prof_finder_history_delete_message);
AlertDialog.Builder adb=new AlertDialog.Builder(HomeActivity.this);
adb.setTitle(title);
adb.setMessage(message);
final int positionToRemove = position;
String positive = resources.getString(R.string.prof_finder_history_delete_positive);
String negative = resources.getString(R.string.prof_finder_history_delete_negative);
adb.setNegativeButton(negative, null);
adb.setPositiveButton(positive, new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ProfBean prof = HomeActivity.this.historyProfs.get(positionToRemove);
HomeActivity.this.db.deleteProf(prof.getProfId());
HomeActivity.this.historyProfs.remove(positionToRemove);
HomeActivity.this.runOnUiThread(new Runnable() {
public void run() {
HomeActivity.this.listAdapter.notifyDataSetChanged();
}
});
}});
adb.show();
return true;
}
});
}
public void searchProf(View view) throws Exception
{
EditText queryEditText = (EditText) this.findViewById(R.id.prof_finder_search_query);
String query = queryEditText.getText().toString().trim();
queryEditText.setText(query);
if (query.length() < 3) {
String message = this.getResources().getString(R.string.prof_finder_query_too_short);
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
return;
}
Intent intent = new Intent(HomeActivity.this, SearchResultActivity.class);
Bundle bundle = new Bundle();
bundle.putString("query", query);
intent.putExtras(bundle);
this.startActivity(intent);
}
public void onResume()
{
super.onResume();
this.historyProfs = this.db.getHistory(-1);
this.listAdapter.notifyDataSetChanged();
}
}
You haven't set any new data to list view. Thats why your new contact isn't added to the list after notifyDataSetChanged(). You need to add some method into adapter like
setData(List<ProfBean> data)
{
this.currentAdaptersList= data;
}
and then call notifyDataSetChanged(). So the final onResume will be :
public void onResume()
{
super.onResume();
this.historyProfs = this.db.getHistory(-1);
this.listAdapter.setData(this.historyProfs);
this.listAdapter.notifyDataSetChanged();
}
Enjoy.
And using onResume() for this task is bad idea. Is better to use onActivityResult.
notifyDataSetChanged() didn't work for me either. I was able to solve this a little bit differently:
I use OnStart() (in a derived class from Fragment)
I use setNotifyOnChange() of the ArrayAdapter:
ListView listView = (ListView) findViewById(R.id.logListView);
listView.setAdapter(logAdapter);
logAdapter.setNotifyOnChange(true);
I create the adapter once:
logAdapter = new ArrayAdapter(activity, android.R.layout.simple_list_item_1, activity.logMessages);
in onViewCreated().
In my Android app I have a list of countries that I can add new entries to at any time when the app is running. This list is held in a database. I have tried several different ways of trying to implement an OnListItemClick but I cannot get it to work. Here is my class containing my list:
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class MainActivity extends Activity
{
private DBManager db;
Cursor cursor;
Button goEdit;
ListView listContent;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.initial_activity);
listContent = (ListView)findViewById(R.id.list);
goEdit = (Button)findViewById(R.id.goedit);
//Open database
db = new DBManager(this);
db.openToRead();
cursor = db.queueAll();
String[] from = new String[]{DBManager.KEY_ID, DBManager.KEY_YEAR, DBManager.KEY_CONTENT, DBManager.KEY_DESC};
int[] to = new int[]{R.id.editcountry, R.id.yeartext, R.id.countrytext};
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
listContent.setAdapter(cursorAdapter);
//go to add/delete screen
goEdit = (Button)findViewById(R.id.goedit);
goEdit.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Log.i("Test", "Now moving to the edit activity");
Intent intent = new Intent(MainActivity.this, EditList.class);
startActivity(intent);
}
});
}
//life cycles
protected void onPause()
{
super.onPause();
db.close();
}
#Override
protected void onDestroy()
{
super.onDestroy();
db.close();
finish();
}
}
Here is my class where I can choose to enter new countries into the list:
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
public class EditList extends Activity
{
private DBManager db;
Cursor cursor;
EditText editCountry, editYear, editDesc;
Button add, delete, back;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editCountry = (EditText)findViewById(R.id.editcountry);
editYear = (EditText)findViewById(R.id.edityear);
editDesc = (EditText)findViewById(R.id.editdesc);
add = (Button)findViewById(R.id.add);
delete = (Button)findViewById(R.id.delete);
back = (Button)findViewById(R.id.backmain);
//Open database and fill it with content, then close it
db = new DBManager(this);
db.openToWrite();
cursor = db.queueAll();
add.setOnClickListener(buttonAddOnClickListener);
delete.setOnClickListener(buttonDeleteAllOnClickListener);
//handle switching back to main screen
Log.i("Test", "back to main");
back = (Button)findViewById(R.id.backmain);
back.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
db.close();
//can't use "finish()" because then the list won't refresh with the new data
Log.i("Test", "Going back to the main screen");
Intent intent = new Intent(EditList.this, MainActivity.class);
startActivity(intent);
}
});
}
//insert new country button
Button.OnClickListener buttonAddOnClickListener = new Button.OnClickListener()
{
#Override
public void onClick(View arg0)
{
Toast.makeText(getApplicationContext(), "Added!", Toast.LENGTH_LONG).show();
int year = Integer.parseInt(editYear.getText().toString());
String country = editCountry.getText().toString();
String desc = editDesc.getText().toString();
db.insert(year, country, desc);
updateList();
//clear text fields after use
editYear.setText(null);
editCountry.setText(null);
editDesc.setText(null);
}
};
//delete all button
Button.OnClickListener buttonDeleteAllOnClickListener = new Button.OnClickListener()
{
#Override
public void onClick(View arg0)
{
Toast.makeText(getApplicationContext(), "Your list has been deleted!", Toast.LENGTH_LONG).show();
db.deleteAll();
updateList();
}
};
private void updateList()
{
cursor.requery();
}
#Override
protected void onDestroy()
{
super.onDestroy();
db.close();
finish();
}
}
I have previously implemented an OnListItemClick in a class where the data was statically held in an array. That class also extended ListActivity, which this one doesn't.
The difference between ListActivity and a standard Activity is that the ListActivity handled the OnItemClickListener interface mapping for you, and just provided an extra callback method. Without ListActivity, you'll need to add that plumbing yourself; i.e.
public class MainActivity extends Activity implements AdapterView.OnItemClickListener
{
...
ListView listContent;
#Override
public void onCreate(Bundle savedInstanceState)
{
...
listContent.setOnItemClickListener(this);
...
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
//Callback logic here for clicked items
}
...
}
In your MainActivity add
#Override
public void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
// a list item is click do whatever you want
}
I have an activity where it contains an ActionBar (with four tabs) a fragment respectively assigned to each of these tabs. In these fragments I've assigned some ListAdapters filled with string values, clickable that furthermore I want to operate. When clicking on an item I want that app to send from that fragment to another. I know that I have to use FragmentManager() and FragmentTransaction() but since I'm new to Android dev I demand of any kind of help, help that is appreciated.
Here's the snippet code of one of the tabs(UserFragment.java):
import android.app.ListFragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
/** This is a listfragment class */
public class UserFragment extends ListFragment
{
/** An array of items to display in ArrayList */
String user_items[] = new String[]
{
"Account",
"Addresses",
"Payment Providers",
"Profile",
"Transactions",
"Wallet"
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
/** Creating array adapter to set data in listview */
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getBaseContext(), android.R.layout.simple_expandable_list_item_1, user_items);
/** Setting the array adapter to the listview */
setListAdapter(adapter);
getListView().setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int pos,
long id)
{
Intent myIntent = new Intent(getActivity().getBaseContext(), Profile.class);
startActivity(myIntent);
}
});
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onStart()
{
super.onStart();
/** Setting the multiselect choice mode for the listview */
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
}
The Profile.java activity code:
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
public class Profile extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_layout);
//Button test = (Button) findViewById(R.id.btnTest);
}
}
You need to define OnItemClickListener for your ListFragment to handle item click events. For example:
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3){
// start your new activity here
}
});
I found what was wrong. After a long search I learnt that if the onCreateView() method is static than it's all good to set listener/s but in this case while we fill an array-adapter of string than it's a no-go since first of first it has to created its View therefore doesn't let the app to make any further listeners. In order to make that available, the onActivityCreated(Bundle) should be initiated/created between onCreateView() and onStart() methods and insert the rest of the code.
Here's the solution to link a ListFragment to another FragmentActivity class:
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
getListView().setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int pos,
long id)
{
Intent myIntent = new Intent(getActivity().getBaseContext(), Profile.class);
startActivity(myIntent);
}
});
}