i am attempting to create this app which has a listView and when i click on an item in the listView it displays more information about the clicked item. I dont know how to fix this problem. i am getting the following from my log
java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.List.get(int)' on a null object reference
at com.example.velvetdev01.parselistclick.MainActivity$1.onItemClick(MainActivity.java:50)
at android.widget.AdapterView.performItemClick(AdapterView.java:310)
and here is my code
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.parse.ParseObject;
import com.parse.ParseQueryAdapter;
import java.util.List;
//import android.widget.ArrayAdapter;
public class MainActivity extends Activity {
private CustomAdapter urgentTodosAdapter;
private ParseQueryAdapter<ParseObject> mainAdapter;
private ListView listView;
List<ParseObject> object;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
mainAdapter = new ParseQueryAdapter<ParseObject>(this, "RestaurantDetail");
urgentTodosAdapter = new CustomAdapter(this);
listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(urgentTodosAdapter);
urgentTodosAdapter.loadObjects();
// Binds the Adapter to the ListView
listView.setAdapter(urgentTodosAdapter);
// Capture button clicks on ListView items
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
// Send single item click data to SingleItemView Class
Intent intent = new Intent(MainActivity.this, SingleItemView.class);
// Pass data "name" followed by the position
intent.putExtra("Name", object.get(i).getString("Name"));
// Open SingleItemView.java Activity
startActivity(intent);
}
});
}
}
and my custom adapter
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.parse.ParseFile;
import com.parse.ParseImageView;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseQueryAdapter;
public class CustomAdapter extends ParseQueryAdapter<ParseObject> {
public CustomAdapter(Context context) {
super(context, new ParseQueryAdapter.QueryFactory<ParseObject>() {
public ParseQuery create() {
ParseQuery query = new ParseQuery("RestaurantDetail");
/* query.whereEqualTo("Name", true);*/
return query;
}
});
}
#Override
public View getItemView(ParseObject object, View v, ViewGroup parent) {
if (v == null) {
v = View.inflate(getContext(), R.layout.activity_main, null);
}
super.getItemView(object, v, parent);
ParseImageView todoImage = (ParseImageView) v.findViewById(R.id.icon);
ParseFile imageFile = object.getParseFile("Logo");
if (imageFile != null) {
todoImage.setParseFile(imageFile);
todoImage.loadInBackground();
}
TextView titleTextView = (TextView) v.findViewById(R.id.textView3);
titleTextView.setText(object.getString("Name"));
return v;
}
}
Here is the class i am trying to display the detailed information
#ParseClassName("RestaurantDetail")
public class SingleItemView extends Activity {
// Declare Variables
protected TextView txtname;
String Name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from singleitemview.xml
setContentView(R.layout.single_item_view);
txtname = (TextView) findViewById(R.id.name);
// Retrieve data from MainActivity on item click event
Intent random1 = getIntent();
// Get the name
Name = random1.getStringExtra("Name");
// Locate the TextView in singleitemview.xml
txtname = (TextView) findViewById(R.id.name);
// Load the text into the TextView
txtname.setText(Name);
}
}
Related
In the following program, When I click on Add button in the options menu a dialog is opened wherein the user enters the data which is then shown in the ListView.
There are a number of problems with his code.
1) age.setText in the Custom Adapter causes the app to crash.Commenting out the age.settext line, it works well for the other two TextViews.
2) When i add data in the list using the dialog the second time, the list gets overwritten and no updation is done.
I want the list to be automatically updated when new data is entered rather than over writing it.
3) The data vanishes away when i restart the app. I want the data to be saved permanently.
Code for Custom Adapter is:
package com.example.sakshi.dialogsandmenus;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.ArrayList;
public class CustomAdapter extends BaseAdapter {
private Context context;
private ArrayList<Data> list;
private LayoutInflater mLayoutInflator;
public CustomAdapter(Context context, ArrayList list){
this.context=context;
this.list=list;
mLayoutInflator = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mLayoutInflator.inflate(R.layout.row,null);
TextView name = (TextView)convertView.findViewById(R.id.name);
TextView age = (TextView)convertView.findViewById(R.id.agedata);
TextView dob = (TextView)convertView.findViewById(R.id.dob);
name.setText(list.get(position).getName());
//age.setText(list.get(position).getAge());
dob.setText(list.get(position).getDate());
return convertView;
}
}
Code for Main Activity is:
package com.example.sakshi.dialogsandmenus;
import android.app.Dialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
import static android.R.id.list;
import static com.example.sakshi.dialogsandmenus.R.id.date;
public class MainActivity extends AppCompatActivity{
ListView listview;
ArrayList<Data> arrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView)findViewById(R.id.list_item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id= item.getItemId();
if(id==R.id.add){
filldialog();
}
return super.onOptionsItemSelected(item);
}
public void filldialog(){
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setCanceledOnTouchOutside(false);
dialog.setContentView(R.layout.dialog_layout);
dialog.show();
Button add = (Button)dialog.findViewById(R.id.additem);
final EditText getnamedata = (EditText)dialog.findViewById(R.id.name);
final EditText getagedata = (EditText)dialog.findViewById(R.id.age);
final DatePicker datePicker = (DatePicker)dialog.findViewById(date);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getname = getnamedata.getText().toString();
int getage = Integer.parseInt(getagedata.getText().toString());
int mm,y,d;
mm=datePicker.getMonth();
y=datePicker.getYear();
d=datePicker.getDayOfMonth();
String getdate = d+"/"+mm+"/"+y;
arrayList = new ArrayList<>();
Data data = new Data();
data.setName(getname);
data.setAge(getage);
data.setDate(getdate);
arrayList.add(data);
CustomAdapter customAdapter = new CustomAdapter(MainActivity.this,arrayList);
listview.setAdapter(customAdapter);
//customAdapter.notifyDataSetChanged();
dialog.dismiss();
}
});
}
}
1) you have to convert the value of age to String before setText
//age.setText(list.get(position).getAge());
age.setText(Integer.toString(list.get(position).getAge()));
2) Every time new Arraylist initilaization
intarrayList = new ArrayList<>();
ArrayList arrayList = new ArrayList<>();
public void filldialog(){
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setCanceledOnTouchOutside(false);
dialog.setContentView(R.layout.dialog_layout);
dialog.show();
Button add = (Button)dialog.findViewById(R.id.additem);
final EditText getnamedata = (EditText)dialog.findViewById(R.id.name);
final EditText getagedata = (EditText)dialog.findViewById(R.id.age);
final DatePicker datePicker = (DatePicker)dialog.findViewById(date);
CustomAdapter customAdapter = new CustomAdapter(MainActivity.this,arrayList);
listview.setAdapter(customAdapter);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getname = getnamedata.getText().toString();
int getage = Integer.parseInt(getagedata.getText().toString());
int mm,y,d;
mm=datePicker.getMonth();
y=datePicker.getYear();
d=datePicker.getDayOfMonth();
String getdate = d+"/"+mm+"/"+y;
Data data = new Data();
data.setName(getname);
data.setAge(getage);
data.setDate(getdate);
arrayList.add(data);
customAdapter.notifyDataSetChanged();
dialog.dismiss();
}
});
enter code here
3) Use Sqlite or anyStorage Option for data saving
You are setting int value directly to setText of ageTextView. You need to convert int to String before you setting a text to TextView.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mLayoutInflator.inflate(R.layout.row,null);
TextView name = (TextView)convertView.findViewById(R.id.name);
TextView age = (TextView)convertView.findViewById(R.id.agedata);
TextView dob = (TextView)convertView.findViewById(R.id.dob);
name.setText(list.get(position).getName());
//age.setText(list.get(position).getAge());
age.setText(String.valueOf(list.get(position).getAge())); // use this it will work
dob.setText(list.get(position).getDate());
return convertView;
}
}
Move these lines outside the onClickListener
arrayList = new ArrayList<>();
CustomAdapter customAdapter = new CustomAdapter(MainActivity.this,arrayList);
listview.setAdapter(customAdapter);
Because whenever you are clicking the button arraylist is initializing again.
I have a problem my custom List view.I have data in hash map and add into array list which is shown in below code.what is my problem is in my hash map contain 20 values and i try set into the list view but first data only display other or not.Thanks advance
This is my CustomAdapter
package com.example.node10.databasetesting;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static com.example.node10.databasetesting.DataBase.*;
public class ListViewEmployee extends AppCompatActivity implements View.OnClickListener {
private SimpleCursorAdapter dataAdapter;
private Button btn_view;
private Button btn_submit;
ArrayList<HashMap<Integer,String>> emp;
HashMap<Integer,String> map;
Set<Integer> keyValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view_employee);
DataBase dataBase=new DataBase(this);
map=new HashMap<>();
map=dataBase.getValueEmpTable();
emp=new ArrayList<HashMap<Integer, String>>();
keyValue=map.keySet();
emp.add(map);
btn_view= (Button) findViewById(R.id.id_btn_emp_view);
btn_view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.id_btn_emp_view){
displayList();
// selectItem();
}
}
private void displayList() {
//create the Arrayt adapter
ListView listview= (ListView) findViewById(R.id.id_listview);
final MyAdapter adapter=new MyAdapter(this,R.layout.custom_listview,emp);
listview.setAdapter(adapter);
}
public class MyAdapter extends ArrayAdapter<HashMap<Integer,String>>{
boolean[] checkBoxState;
ViewHolder viewholder;
public MyAdapter(Context context, int resource,ArrayList<HashMap<Integer,String>> map) {
super(context, resource, map);
// create the boolean array for check box selection
checkBoxState= new boolean[map.size()];
}
// create the class for caching the view
class ViewHolder{
TextView txtView;
CheckBox checkBox;
}
#Override
public View getView( final int position, View convertView, ViewGroup parent) {
if(convertView==null){
LayoutInflater objlayout= (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView=objlayout.inflate(R.layout.custom_listview,null);
viewholder=new ViewHolder();
viewholder.txtView= (TextView) convertView.findViewById(R.id.id_checkbox_textview);
viewholder.checkBox= (CheckBox) convertView.findViewById(R.id.id_checkbox);
convertView.setTag(viewholder);
}else{
viewholder = (ViewHolder) convertView.getTag();}
// viewholder.txtView.setText(emp.get(position).toString());
viewholder.txtView.setText(emp.get(position).get(position+1).toString());
viewholder.checkBox.setChecked(checkBoxState[position]);
viewholder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkBoxState[position] = true;
} else {
checkBoxState[position] = false;
}
}
});
return convertView;
}
}
}
Now you put to your adapter ArrayList of HashMap. I don't know why are you doing that, but now your ArrayList emp contains ony one element - that was added in line
emp.add(map);
So, ArrayAdapter for array with size = 1 will show 1 elemet.
If you want to show in list all elements from your map. I suggest to use
ArrayList emp and comvert map to list by using map.values()
ArrayList<String> emp = (ArrayList<String>)map.values();
Then change your adapter to
public class MyAdapter extends ArrayAdapter<String>
Can someone please help me? I am trying to access a "position" variable itemclicked. I want the content of the other class to display a different thing depending on the list I clicked.
What I want is this: if I click position 0, then it takes me to another page and the TextView I created on that class changes to "you clicked position 0". If I click position 1, it changes to "you clicked position 1", etc.
I've attempted to do this, but it only works when I click position 0. If I click item 1, it shows "you have clicked position 0". I am very confused. I have tried using putexraa and other methods, but they are not working. Your help would be greatly appreciated.
package com.obi.arinzeapp;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
private List<list> mymusic = new ArrayList<list>();
public list currentsong;
public int man;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
populatemusiclist();
populateListView();
registerclick();
}
private void registerclick() {
ListView mus = (ListView) findViewById(R.id.musiclistview);
mus.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long arg3) {
man = position;
try {
Class ourClass = Class.forName("com.obi.arinzeapp.Music");
Intent ourIntent = new Intent(MainActivity.this, ourClass);
startActivity(ourIntent);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
});
}
private void populatemusiclist() {
mymusic.add(new list(R.drawable.ff, " Mr.J.Mederiors \"Constance\"",
R.drawable.medi));
mymusic.add(new list(R.drawable.ff, " Mr.J.Mederiors \"Constnce\"",
R.drawable.medi));
mymusic.add(new list(R.drawable.ff, " Mr.J.Mederiors \"Constnce\"",
R.drawable.medi));
}
private void populateListView() {
ArrayAdapter<list> adapter = new MyListAdapter();
ListView list = (ListView) findViewById(R.id.musiclistview);
list.setAdapter(adapter);
}
private class MyListAdapter extends ArrayAdapter<list> {
public MyListAdapter() {
super(MainActivity.this, R.layout.viewitem, mymusic);
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View veiwitem = convertView;
if (veiwitem == null) {
veiwitem = getLayoutInflater().inflate(R.layout.viewitem,
parent, false);
// return super.getView(position, convertView, parent);
}
list currentsong = mymusic.get(position);
ImageView imageview = (ImageView) veiwitem
.findViewById(R.id.imageView2);
imageview.setImageResource(currentsong.getNum());
TextView wor = (TextView) veiwitem.findViewById(R.id.word);
wor.setText(currentsong.getNameofsong());
ImageView imageview2 = (ImageView) veiwitem
.findViewById(R.id.imageView1);
imageview2.setImageResource(currentsong.getPicture());
return veiwitem;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
import android.app.Activity;
import android.os.Bundle;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class Music extends Activity{
TextView name,song,album,about;
String nam,son,albu,abou;
RelativeLayout picc;
public int ye ;
MainActivity maa = new MainActivity();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stu
super.onCreate(savedInstanceState);
setContentView(R.layout.music);
name= (TextView) findViewById(R.id.name);
song= (TextView) findViewById(R.id.song);
album=(TextView) findViewById(R.id.album);
about=(TextView) findViewById(R.id.about);
picc=(RelativeLayout) findViewById(R.id.picc);
maa.man= ye;
if(ye==0){
name.setText("You clicked position 1") ;
}else{
name.setText("You clicked position 2") ;
}
}
}
Pass the value of man in putExtra while setting the intent for that class in mainActivity
Class ourClass = Class.forName("com.obi.arinzeapp.Music");
Intent ourIntent = new Intent(MainActivity.this, ourClass);
ourIntent.putExtra("man",man);
startActivity(ourIntent);
And get this extra in Music Activity
extras = getIntent().getExtras();
newInt= extras.getInt("man");
This is the standard way to pass the values from one activity to another.
But the way you doing you can try making man as static variablebut it is not recommended.
I was just wondering if I was able to start a new activity with the click of an item inside a ListView.
The code I have written so far:
package awad865.project.ContactManager1;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.example.contactmanager1.R;
import android.widget.AdapterView;
public class MainActivity extends Activity {
private ListView listView;
private ImageButton button1;
private ImageButton button2;
private ImageButton button3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getActionBar().setDisplayShowTitleEnabled(false);
getActionBar().setDisplayShowHomeEnabled(false);
listView = (ListView)findViewById(R.id.main_contact_listview);
button1= (ImageButton)findViewById(R.id.button_search);
button2= (ImageButton)findViewById(R.id.button_addcontact);
button3= (ImageButton)findViewById(R.id.button_options);
setUpListView();
}
private void setUpListView(){
List <Contact> displayList = new ArrayList<Contact>();
displayList.add(new Contact("Anmol","Wadhwa","53743632"));
displayList.add(new Contact("Juhi","Goswami","4234232"));
displayList.add(new Contact("Laurence","Baldwick","243232"));
ListAdapter listAdapter = new CustomListAdapter(MainActivity.this,displayList);
listView.setAdapter(listAdapter);
}
private class CustomListAdapter extends ArrayAdapter<Contact>{
private Context _context;
private List<Contact> _contacts;
public CustomListAdapter(Context context, List<Contact> contacts){
super(context,android.R.layout.simple_list_item_1,contacts);
_context = context;
_contacts = contacts;
}
public View getView(int position, View convertView,ViewGroup parent){
//Create a layout inflater to inflate our xml layout for each item in the list
LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//Inflate the list item layout. Keep a reference to the inflated view.
//No root view specified
View listItemView = inflater.inflate(R.layout.custom_list_item_layout,null);
//Access TextView elements inside the view (note we must specify the parent view
//to look in)
TextView firstName = (TextView)listItemView.findViewById(R.id.list_item_firstname);
TextView lastName = (TextView)listItemView.findViewById(R.id.list_item_lastname);
TextView number = (TextView)listItemView.findViewById(R.id.list_item_number);
//Set the text for each textview (use the position arugment to find the appropriate element in the list)
firstName.setText(_contacts.get(position).getFirstName());
lastName.setText(_contacts.get(position).getLastName());
number.setText(_contacts.get(position).getNumber());
return listItemView;
}
}
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.action_groups:
Intent groupIntent = new Intent(this,Groups.class);
startActivity(groupIntent);
return true;
case R.id.action_favourites:
Intent favouriteIntent = new Intent(this,Favourites.class);
startActivity(favouriteIntent);
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_activity_actions, menu);
return true;
}
public void addContact(View view){
Intent intent = new Intent(this,AddContact.class);
startActivity(intent);
}
}
class listItemClickedListener implements AdapterView.OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> parentView, View clickedView, int clickedViewPosition, long id) {
// TODO Auto-generated method stub
Intent contactInfoIntent = new Intent(this, ContactInformation.class);
}
}
I was just wondering if I was able to start a new activity inside the method onItemClick() in the class listItemClickListener. Any help would be appreciated because the compiler doesn't allow me to start a new intent.
You can retrieve the Context you need from clickedView.
Intent contactInfoIntent = new Intent(clickedView.getContext(), ContactInformation.class);
clickedView.getContext().startActivity(contactInfoIntent);
start Activity on ListView item Click as:
STEP 1:
Add on OnItemClickListener by passing instace of listItemClickedListener class as:
....
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new listItemClickedListener());
STEP 2:
start Activity from onItemClick as:
Intent contactInfoIntent = new Intent(clickedView.getContext(),
ContactInformation.class);
clickedView.getContext().startActivity(contactInfoIntent);
you need to bind the click event to each item added to the listView
You could put the Data, in your case ContactDate, as a ContactData element onto your View (each cell) by calling convertView.setTag(contactData) in your getView() Method.
onItemClick wpuld then do something like this:
ContactData cd = (ContactData)clickedView.getTag();
Bundle b = new Bundle();
// put data from cd in that Bundle
Intent contactInfoIntent = new Intent(this, ContactInformation.class);
startActivity(contactInfoIntent);
update:
try this:
package awad865.project.ContactManager1;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.example.contactmanager1.R;
import android.widget.AdapterView;
public class MainActivity extends Activity implements OnItemClickListener{
private ListView listView;
private ImageButton button1;
private ImageButton button2;
private ImageButton button3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getActionBar().setDisplayShowTitleEnabled(false);
getActionBar().setDisplayShowHomeEnabled(false);
listView = (ListView)findViewById(R.id.main_contact_listview);
button1= (ImageButton)findViewById(R.id.button_search);
button2= (ImageButton)findViewById(R.id.button_addcontact);
button3= (ImageButton)findViewById(R.id.button_options);
setUpListView();
}
private void setUpListView(){
List <Contact> displayList = new ArrayList<Contact>();
displayList.add(new Contact("Anmol","Wadhwa","53743632"));
displayList.add(new Contact("Juhi","Goswami","4234232"));
displayList.add(new Contact("Laurence","Baldwick","243232"));
ListAdapter listAdapter = new CustomListAdapter(MainActivity.this,displayList);
listView.setAdapter(listAdapter);
}
private class CustomListAdapter extends ArrayAdapter<Contact>{
private Context _context;
private List<Contact> _contacts;
public CustomListAdapter(Context context, List<Contact> contacts){
super(context,android.R.layout.simple_list_item_1,contacts);
_context = context;
_contacts = contacts;
}
public View getView(int position, View convertView,ViewGroup parent){
//Create a layout inflater to inflate our xml layout for each item in the list
LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//Inflate the list item layout. Keep a reference to the inflated view.
//No root view specified
if (convertView == null)
View convertView = inflater.inflate(R.layout.custom_list_item_layout,null);
//Access TextView elements inside the view (note we must specify the parent view
//to look in)
TextView firstName = (TextView)convertView.findViewById(R.id.list_item_firstname);
TextView lastName = (TextView)convertView.findViewById(R.id.list_item_lastname);
TextView number = (TextView)convertView.findViewById(R.id.list_item_number);
//Set the text for each textview (use the position arugment to find the appropriate element in the list)
firstName.setText(_contacts.get(position).getFirstName());
lastName.setText(_contacts.get(position).getLastName());
number.setText(_contacts.get(position).getNumber());
//TODO add your data to the View
convertView.setTag(yourData)
return convertView;
}
}
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.action_groups:
Intent groupIntent = new Intent(this,Groups.class);
startActivity(groupIntent);
return true;
case R.id.action_favourites:
Intent favouriteIntent = new Intent(this,Favourites.class);
startActivity(favouriteIntent);
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_activity_actions, menu);
return true;
}
public void addContact(View view){
Intent intent = new Intent(this,AddContact.class);
startActivity(intent);
}
Override
public void onItemClick(AdapterView<?> parentView, View clickedView, int clickedViewPosition, long id) {
ContactData cd = (ContactData)clickedView.getTag();
Bundle b = new Bundle();
// TODO put data from cd in that Bundle
Intent contactInfoIntent = new Intent(this, ContactInformation.class);
startActivity(contactInfoIntent);
}
}
besides, you usually do iOS development or am i wrong?
First argument of an Intent constructor requires an object of Context class. But you supplied an listItemClickedListener.class.
Intent constructor requeres:
Intent(Context, Class<?>)
you supplied:
Intent(listItemClickedListener, Class<?>)
I've written a big code and I've used a list view within one of my task layouts :
I want to know how I can make a listener for each update button in this case in order to move to another activity , I know how to use more than one activity and moves between them But I want to know how to make a listener only .
The custom adapter code :
package com.example.task_9;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class TempLyaout extends ArrayAdapter<String> {
Context context;
ArrayList<String> sa;
public TempLyaout(Context context , ArrayList<String> sa) {
super(context,R.layout.temp,sa);
this.context=context;
this.sa = sa;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater l = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View rowView = l.inflate(R.layout.temp, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.textView1);
ImageView imageView = (ImageView) rowView.findViewById(R.id.imageView1);
Button update = (Button) rowView.findViewById(R.id.button1);
// myDb.open();
// Cursor cursor= myDb.getRowByName(sa.get(position));
// myDb.updateRowByName(cursor.getInt(DBAdapter.COL_ROWID), sa.get(position), cursor.getString(DBAdapter.COL_PASSWD), cursor.getInt(DBAdapter.COL_AGE), isAdmin);
// myDb.close();
textView.setText(sa.get(position));
return rowView;
}
}
This is the related class :
package com.example.task_9;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class UsersActivity extends Activity {
Intent redirect;
ListView list;
ArrayList<String> sa;
DBAdapter myDb;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
#Override
protected void onStart() {
super.onStart();
setContentView(R.layout.users);
list= (ListView) findViewById(R.id.usersList);
redirect = getIntent();
openDB();
/*********************************************/
Cursor cursor = myDb.getAllRows();
cursor.moveToFirst();
ArrayList<String> ha = new ArrayList<String>();
while(cursor.moveToNext()) {
ha.add(cursor.getString(DBAdapter.COL_NAME));
}
cursor.close();
#SuppressWarnings("rawtypes")
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,ha);
list.setAdapter(new TempLyaout(UsersActivity.this,ha));
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"Click ListItem Number " + position, Toast.LENGTH_LONG)
.show();
}
});
} // end onStart method
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
#Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}// end onDestroy method
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
private void openDB() {
myDb = new DBAdapter(this);
myDb.open();
} // end openDB method
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
private void closeDB() {
myDb.close();
} // end closeDB method
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
}// end main class
In your getView
Button update = (Button) rowView.findViewById(R.id.button1);
update.setOnClickListener(mClickListener);
Then
private OnClickListener mClickListener = new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(ListActivtiy.this,SecondActivity.class);
startActivity(intent);
}
};
Also use a viewholder for smooth scrolling and performance
http://developer.android.com/training/improving-layouts/smooth-scrolling.html