Change Value Of ListItem onItemClick - android

I want to change the value of listItem when that listItem is clicked. I have provided the code below.
public class MyListDialogExampleActivity extends Activity implements OnItemClickListener {
ListView myListView;
String itemString = null;
String [] listViewArray = new String[] {"ABC", "DEF", "GHI", "JKL"};
MyArrayAdapter listAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myListView = (ListView) findViewById (R.id.myListView);
listAdapter = new MyArrayAdapter(this, R.layout.list_row, R.id.list_tv, listViewArray);
myListView.setAdapter(listAdapter);
myListView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
Log.d("onItemClick", arg2+"");
String str = showListDialog();
// i want to change the selected list item with String str
}
public String showListDialog () {
final CharSequence[] items = {"1", "2", "3", "4"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a number");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
itemString = items[item].toString();
}
});
AlertDialog alert = builder.create();
alert.show();
return itemString;
}
}

you need to use the parameters sent to you on the onItemClick , so that you take the i-th element in the array you've used , change its value , and in the end , notify the adapter that the data has changed by using notifyDatasetChanged.

You can't change arrays during runtime
So you have to use List (http://developer.android.com/reference/java/util/List.html)

Related

Object cannot be converted to int

I am going to delete the specific data from list view after building the gradle there's an error says "error: incompatible types: Object cannot be converted to int"
Code of DatabaseHelper
public void deletegroce(int groceId){
String groceid[] = { String.valueOf(groceId) };
SQLiteDatabase sqdb = this.getWritableDatabase();
sqdb.delete(TABLE_NAME, KEY_GROCE_ID + " = ?", groceid);
sqdb.close();
}
And here's my full code of Grocery_List and the error is located at line 65 which is "int dave = aList.get(position); dbhelper.deletegroce(dave);"
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grocery_list);
lvGorc = (ListView) findViewById(R.id.lvGroc);
dbhelper = new DatabaseHelper(Grocery_list.this);
final List aList = dbhelper.getAllGroceries();
final ArrayAdapter<String> La = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, aList);
lvGorc.setAdapter(La);
lvGorc.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(final AdapterView<?> adapterView, View view, int i, long l) {
AlertDialog.Builder adb = new AlertDialog.Builder(Grocery_list.this);
adb.setTitle("Option");
adb.setMessage("What do you want to do?");
adb.setPositiveButton("Update", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
adb.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
adb.show();
}
});
lvGorc.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder adb = new AlertDialog.Builder(Grocery_list.this);
adb.setTitle("Delete?");
adb.setMessage("Are you sure you want to delete the selected item?");
adb.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
int dave = aList.get(position);
dbhelper.deletegroce(dave);
La.notifyDataSetChanged();
}
});
adb.show();
return true;
}
});
}
The aList you have defined is a List of objects. the ArrayAdapter<String> accepts all kind of objects lists and it will call toString() method, which all objects have it, to show it in the ListView.
When you try to get an object of aList it returns an object of that index which can not be cast to int.
I think you can simply take the id of your object and pass it into the dbhelper.deletegroce(dave). if your aList is a List of Integer objects you can simply cast it to int by calling:
int dave = (int) aList.get(position);
Your 5th line in OnCreate method which says
final List aList = dbhelper.getAllGroceries();
it doesn't specify that aList is List of Integer. What does your getAllGroceries return?
You should also define your list as final List aList = dbhelper.getAllGroceries();
and make sure dbhelper.getAllGroceries() return List of Integer data.

Remove item from another activity using button

The problem: I want to remove a item from my listview using a button in another activity.
I have tried several kinds of code, but it just doesn't seem to work.
Right know I use serializable to bundle the object to the other activity.
But I don't know how to remove it, from the other activity.
Can anybody help me with that?
Can I use the button from the second activity, in the first activity to delete the item from the listview?
Class A where I got my ListView
public class ListActivity extends Activity {
ListView list;
Button exit;
SimpleAdapter adapter;
final List<Map<String, String>> data = new ArrayList<Map<String, String>>();
#Override``
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
list = (ListView) findViewById(R.id.list);
exit = (Button) findViewById(R.id.btnExit);
// Registration numbers
final String[] title = new String[] { "XMT 123", "KLE 456", "CKL 789",
"MRP 012", "DSV 345" };
// Name of the truck drivers
final String[] subtitle = new String[] { "Peter Lund", "Hans Larsson",
"Erik Petersson", "Bjørn Lundal", "Lars Svensson" };
for (int i = 0; i < title.length; i++) {
Map<String, String> datalist = new HashMap<String, String>();
datalist.put("title", title[i]);
datalist.put("subtitle", subtitle[i]);
data.add(datalist);
}
// getDataInList();
adapter = new SimpleAdapter(this, data,
android.R.layout.simple_list_item_2, new String[] { "title",
"subtitle" }, new int[] { android.R.id.text1,
android.R.id.text2 });
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
Intent intent = new Intent(ListActivity.this,
InformationActivity.class);
intent.putExtra("updateReg", title[position].toString());
intent.putExtra("updateName", subtitle[position].toString());
}
});
exit.setOnClickListener(new OnClickListener() {
// Closes the application
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
Class B where I got my accept button.
When I click accept, the item from the listview in Class A should be removed.
public class InformationActivity extends Activity {
TextView name;
TextView reg;
TextView product;
TextView productNo;
Button accept;
Button edit;
Button exit;
AlertDialog dialog;
ListView list;
String result;
EditText search;
int requestCode = 1;
SimpleAdapter adapter;
Context context = InformationActivity.this;
ArrayList<Materials> materialList = new ArrayList<Materials>();
// Materials
final static String[] material = new String[] { "Betong", "Grus", "Järn",
"Metall", "Grus fin", "Grus grov", "Sten" };
// Material numbers
final static String[] materialNo = new String[] { "123", "234", "345",
"456", "567", "789", "012" };
private void getDataInList() {
for (int i = 0; i < 7; i++) {
Materials mats = new Materials(result, result);
mats.setMaterialName(material[i]);
// mats.setMaterialNo(material[i]);
materialList.add(mats);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.information_activity);
name = (TextView) findViewById(R.id.name);
reg = (TextView) findViewById(R.id.reg);
product = (TextView) findViewById(R.id.product);
productNo = (TextView) findViewById(R.id.productNo);
accept = (Button) findViewById(R.id.btnAccept);
edit = (Button) findViewById(R.id.btnEdit);
list = (ListView) findViewById(R.id.list);
Bundle extras = getIntent().getExtras();
String selected_item = extras.getString("updateReg");
reg = (TextView) findViewById(R.id.reg);
reg.setText(selected_item);
Bundle extras1 = getIntent().getExtras();
String selected_item1 = extras1.getString("updateName");
name = (TextView) findViewById(R.id.name);
name.setText(selected_item1);
getDataInList();
edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder popup = new AlertDialog.Builder(
InformationActivity.this);
popup.setTitle("Välj ny artikel");
// Search field
final EditText search = new EditText(context);
popup.setView(search);
search.setHint("Sök här...");
popup.setSingleChoiceItems(material, -1,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
materialList.get(which);
Toast.makeText(getApplicationContext(),
material[which], Toast.LENGTH_SHORT)
.show();
result = material[which];
}
});
// PositiveButton, updates the material info field.
popup.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
product.setText(result);
}
});
// NegativeButton, closes the pop-up.
popup.setNegativeButton("Avbryt",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
dialog = popup.create();
dialog.show();
}
});``
//Remove item
accept.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
You should not directly remove the item from the view, but from the data displayed in it.
For example if your ListView is displaying items from an ArrayList, just remove the item in the ArrayList from you Activity B, and call myAdapter.notifyDataSetChanged() when back in the Activity A, which contains the adapter.
You can remove items by accessing to the ArrayList or by overriding the remove() method if you have only access to the adapter (assuming your adapter extends ArrayAdapter).
Also, you may have to override usefull Adapter methods like getCount(), getView()...
Thanks to all.
I found another solution thanks to remove row from another activity
Class A
public class ListActivity extends Activity {
ListView list;
Button exit;
static List<ListItems> items = new ArrayList<ListItems>();
public static int deletePos;
static ListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
list = (ListView) findViewById(R.id.list);
exit = (Button) findViewById(R.id.btnExit);
// Registration numbers
final String[] title = new String[] { "XMT 123", "KLE 456", "CKL 789",
"MRP 012", "DSV 345" };
// Name of the truck drivers
final String[] subtitle = new String[] { "Peter Lund", "Hans Larsson",
"Erik Petersson", "Bjørn Lundal", "Lars Svensson" };
items = new ArrayList<ListItems>();
for (int i = 0; i < title.length; i++) {
ListItems s = new ListItems(title[i], subtitle[i]);
items.add(s);
}
adapter = new ListAdapter(this, android.R.layout.simple_list_item_2,
items);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
Intent intent = new Intent(ListActivity.this,
InformationActivity.class);
intent.putExtra("updateReg", title[position].toString());
intent.putExtra("updateName", subtitle[position].toString());
deletePos = position;
adapter.notifyDataSetChanged();
startActivity(intent);
}
});
exit.setOnClickListener(new OnClickListener() {
// Closes the application
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
}
Class B
public class InformationActivity extends Activity {
TextView name;
TextView reg;
TextView product;
TextView productNo;
Button accept;
Button edit;
Button exit;
AlertDialog dialog;
ListView list;
String result;
EditText search;
Context context = InformationActivity.this;
ArrayList<Materials> materialList = new ArrayList<Materials>();
// Materials
final static String[] material = new String[] { "Betong", "Grus", "Järn",
"Metall", "Grus fin", "Grus grov", "Sten" };
// Material numbers
final static String[] materialNo = new String[] { "123", "234", "345",
"456", "567", "789", "012" };
private void getDataInList() {
for (int i = 0; i < 7; i++) {
Materials mats = new Materials(result, result);
mats.setMaterialName(material[i]);
// mats.setMaterialNo(material[i]);
materialList.add(mats);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.information_activity);
name = (TextView) findViewById(R.id.name);
reg = (TextView) findViewById(R.id.reg);
product = (TextView) findViewById(R.id.product);
productNo = (TextView) findViewById(R.id.productNo);
accept = (Button) findViewById(R.id.btnAccept);
edit = (Button) findViewById(R.id.btnEdit);
list = (ListView) findViewById(R.id.list);
Bundle extras = getIntent().getExtras();
String selected_item = extras.getString("updateReg");
reg = (TextView) findViewById(R.id.reg);
reg.setText(selected_item);
Bundle extras1 = getIntent().getExtras();
String selected_item1 = extras1.getString("updateName");
name = (TextView) findViewById(R.id.name);
name.setText(selected_item1);
getDataInList();
edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder popup = new AlertDialog.Builder(
InformationActivity.this);
popup.setTitle("Välj ny artikel");
// Search field
final EditText search = new EditText(context);
popup.setView(search);
search.setHint("Sök här...");
popup.setSingleChoiceItems(material, -1,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
materialList.get(which);
Toast.makeText(getApplicationContext(),
material[which], Toast.LENGTH_SHORT)
.show();
result = material[which];
}
});
// PositiveButton, updates the material info field.
popup.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
product.setText(result);
}
});
// NegativeButton, closes the pop-up.
popup.setNegativeButton("Avbryt",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
dialog = popup.create();
dialog.show();
}
});
// Remove item
accept.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int deletePos = ListActivity.deletePos;
ListActivity.items.remove(deletePos);
ListActivity.adapter.notifyDataSetChanged();
finish();
}
});
}
}

loading a default image using bitmap factory inside list view Adapter Class

i am calling a web service to get some details and show them in a list view.now i have to show a image on that list view. i can retrieve the image url from JSON object. but when the image url contains null , i want to show a defult image in the list view. i know below code is the code segment which is use to that.but since im going to handle this inside of my adapter class (extends by BaseAdapter Class) i cant use it.. please guide me how to handle this...
here my Adapter class
public class NewsRowAdapter extends BaseAdapter {
static Dialog dialogs;
private static final String STIME = "StartTime";
private static final String END = "EndTime";
private static final String DATE = "Date";
private Context mContext;
private Activity activity;
private static LayoutInflater inflater=null;
private ArrayList<HashMap<String, String>> data;
int resource;
public ImageLoader imageLoader;
//String response;
//Context context;
//Initialize adapter
public NewsRowAdapter(Context ctx,Activity act, int resource,ArrayList<HashMap<String, String>> d) {
super();
this.resource=resource;
this.data = d;
this.activity = act;
this.mContext = ctx;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public void showFirstDialog(final ArrayList<HashMap<String, String>> list){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(activity);
alertDialogBuilder.setTitle("Confirm your Action!");
// set dialog message
alertDialogBuilder
.setMessage("You Have Similar Kind of Appoinments!! Do you wanna Show them ?")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
Toast.makeText(mContext, "Showing", Toast.LENGTH_LONG).show();
dialogpop(list);
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
alertDialogBuilder.show();
}
public void dialogshow(final String Date,final String Start,final String End){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(activity);
alertDialogBuilder.setTitle("Confirm your Action!");
// set dialog message
alertDialogBuilder
.setMessage("Click yes Confirm!!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
//MainActivity.this.finish();
Toast.makeText(mContext, "Yes clicked", Toast.LENGTH_LONG).show();
//check similer records
//if duplicates > 1 then show the popup list
//if(duplicateList.size()>1){
/*final Dialog dialogs = new Dialog(activity);
dialogs.setContentView(R.layout.dialog_list);
dialogs.setTitle("Select One");
ListView listView = (ListView) dialogs.findViewById(R.id.dialogList);
NewsRowAdapter nw = new NewsRowAdapter(mContext, activity, R.layout.dialog_row, duplicateList);
listView.setAdapter(nw);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0,
View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
dialogs.dismiss();
}
});
dialogs.show();*/
// }
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
alertDialogBuilder.show();
}
public void showDuplicateDialog(ArrayList<HashMap<String, String>> list){
//CharSequence[] cs = list.toArray(new CharSequence[list.size()]);
AlertDialog.Builder alertDialogBuilder2 = new AlertDialog.Builder(activity);
LayoutInflater infl = activity.getLayoutInflater();
View view = infl.inflate(R.layout.dialog_list, null);
ListView lv = (ListView) view.findViewById(R.id.dialogList);
//NewsRowAdapter nw = new NewsRowAdapter(mContext, activity, R.layout.dialog_row, list);
SimpleAdapter sim = new SimpleAdapter(mContext, list, R.layout.dialog_row, new String[] { STIME,END, DATE }, new int[] {
R.id.stime2,R.id.etime2, R.id.blank2});
lv.setAdapter(sim);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(mContext, "item clicked ", Toast.LENGTH_LONG).show();
}
});
/*ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.two_line_list_item, android.R.id.text1, Names);*/
alertDialogBuilder2.setView(view)
/*alertDialogBuilder2.setAdapter(sim, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(mContext, "item clicked ", Toast.LENGTH_LONG).show();
}
})
*/
.setPositiveButton("Accept", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(mContext, "Accepted", Toast.LENGTH_LONG).show();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
alertDialogBuilder2.show();
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View vi = convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.row,null);
final TextView firstname = (TextView) vi.findViewById(R.id.fname);
final TextView lastname = (TextView) vi.findViewById(R.id.lname);
final TextView startTime = (TextView) vi.findViewById(R.id.stime);
final TextView endTime = (TextView) vi.findViewById(R.id.etime);
final TextView date = (TextView) vi.findViewById(R.id.blank);
final TextView hidID = (TextView) vi.findViewById(R.id.hidenID);
final ImageView img = (ImageView) vi.findViewById(R.id.list_image);
HashMap<String, String> song = new HashMap<String, String>();
song =data.get(position);
firstname.setText(song.get(MainActivity.TAG_PROP_FNAME));
lastname.setText(song.get(MainActivity.TAG_PROP_LNAME));
startTime.setText(song.get(MainActivity.TAG_STIME));
endTime.setText(song.get(MainActivity.TAG_ETIME));
date.setText(song.get(MainActivity.TAG_DATE));
hidID.setText(song.get(MainActivity.TAG_HID));
String theUrl = song.get(MainActivity.TAG_IMG);
if(theUrl.equalsIgnoreCase("null")){
/*Bitmap bImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.propic);
profPic.setImageBitmap(bImage);
ViewList v = new ViewList();
v.handleImage(theUrl, img);*/
}
else{
imageLoader.DisplayImage(song.get(MainActivity.TAG_IMG), img);
}
Button accept = (Button) vi.findViewById(R.id.btnAccepted);
accept.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final int x = (int) getItemId(position);
/*Intent zoom=new Intent(mContext, Profile.class);
zoom.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
zoom.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(zoom);*/
// get the intent from the hashmap check if there is similar date and time.
//then store them in a list or array.
String getDate = (String) date.getText();
String getStartTime = startTime.getText().toString();
String getEndTime = endTime.getText().toString();
ShortList sh = new ShortList();
ArrayList<HashMap<String, String>> duplicateList;
duplicateList=sh.getDuplicated(getDate, getStartTime, getEndTime);
if(duplicateList.size()>1){
//dialogshow(getDate,getStartTime,getEndTime);
showFirstDialog(duplicateList);
}
else{
dialogshow(getDate, getStartTime, getEndTime);
}
}
});
vi.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String getPname = hidID.getText().toString();
Toast.makeText(parent.getContext(), "view clicked: "+getPname , Toast.LENGTH_SHORT).show();
//get the id of the view
//check the id of the request
//call the web service acording to the id
Intent zoom=new Intent(parent.getContext(), Profile.class);
zoom.putExtra("PatientID", getPname);
parent.getContext().startActivity(zoom);
}
});
return vi;
}
public void dialogpop(ArrayList<HashMap<String, String>> list){
dialogs = new Dialog(activity);
dialogs.setContentView(R.layout.dialog_list);
dialogs.setTitle("Select One");
ListView listView = (ListView) dialogs.findViewById(R.id.dialogList);
//SimpleAdapter sim = new SimpleAdapter(mContext, list, R.layout.dialog_row, new String[] { STIME,END, DATE }, new int[] {
// R.id.stime2,R.id.etime2, R.id.blank2});
Adapter_For_Dialog nw = new Adapter_For_Dialog(mContext,activity, R.layout.dialog_row, list);
listView.setAdapter(nw);
dialogs.show();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int possision) {
// TODO Auto-generated method stub
return possision;
}
#Override
public long getItemId(int possision) {
// TODO Auto-generated method stub
return possision;
}
}
please help me :)
My problem is i cant use this code segment in my adapter Class
Bitmap bImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.propic);
profPic.setImageBitmap(bImage);
Replace
if(theUrl.equalsIgnoreCase("null")){
with
if(theUrl==null || theUrl.equals("")){
and check if it works or not

Spinner is not working in android

Spinner is not working. Here is my code:
public class second extends Activity{
Spinner spin;
String[] str;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
spin = (Spinner) findViewById(R.id.spin);
str = new String[] {"bike","car"};
spin.setAdapter(new ArrayAdapter<CharSequence>(this, android.R.layout.simple_dropdown_item_1line, str));
spin.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View view, int pos,
long id) {
// TODO Auto-generated method stub
String data= spin.getItemAtPosition(pos).toString();
Toast.makeText(second.this, data, Toast.LENGTH_SHORT).show();
}
});
}
}
The only mistake you made is you have set different event listener..
The Listener OnItemClickListener is for ListView..
For Spinner you have to set OnItemSelectedListener ..
Try replacing OnItemClickListener to setOnItemSelectedListener like :
spin.setOnItemSelectedListener (new OnItemSelectedListener() {
public void onItemClick(AdapterView<?> adapter, View view, int pos,
long id) {
// TODO Auto-generated method stub
String data= spin.getItemAtPosition(pos).toString();
Toast.makeText(second.this, data, Toast.LENGTH_SHORT).show();
}
});
The problem is here,
spin.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View view, int pos,
long id) {
// TODO Auto-generated method stub
String data= spin.getItemAtPosition(pos).toString();
Toast.makeText(second.this, data, Toast.LENGTH_SHORT).show();
}
});
Try replacing it as follows,
spin.OnItemSelectedListener (new OnItemSelectListener() {
public void onItemSelect(AdapterView<?> adapter, View view, int pos,
long id) {
// TODO Auto-generated method stub
String data= spin.getItemAtPosition(pos).toString();
Toast.makeText(second.this, data, Toast.LENGTH_SHORT).show();
}
});
Here is the problem in your oncreate() method:
spin = (Spinner) findViewById(R.id.spin);
You assign the result to spinner which is a local variable/reference here. main.spinner class field is still null. This is why you have NullPointerException in calculate() method.
Replace the line above with:
this.spin = (Spinner) findViewById(R.id.spin);
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item,androidBooks);
spin.setAdapter(adapter);
Try this one
spinner = (Spinner) findViewById(R.id.spinner);
List<String> categories = new ArrayList<String>();
categories.add("--Qualification--");
categories.add("High School");
categories.add("Higher Secondary/PUC");
categories.add("Diploma");
categories.add("Degree");
categories.add("Master Degree");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.spinnertext, categories);
adapter.setDropDownViewResource(android.R.layout.select_dialog_item);
spinner.setAdapter(adapter);
Check Out on this link

popup menu for spinner in android

i want a spinner with items'A','B','C'
if u select 'A' or'B' means the chronometer has to run.
while select the item 'C' the popup window has 2 open with edittext and 'Ok' button..
if you type the'D' in the edittext means that has too add in the spinner while add the chonometer has to run
here is my code:
public class Starttracker extends Activity {
PopupWindow popupWindow;
String[] Items = {
"A",
"B",
"C",
"D",
};
Spinner s1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start);
s1 = (Spinner) findViewById(R.id.spinner);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this,android.R.layout.simple_spinner_item,Items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> arg0,
View arg1, int arg2, long arg3)
{
int index = s1.getSelectedItemPosition();
Toast.makeText(getBaseContext(),
"You have selected item : " + Items[index],
Toast.LENGTH_SHORT).show();
if (index==3)
{
LayoutInflater inflater = (LayoutInflater) Starttracker.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
popupWindow = new PopupWindow(inflater.inflate(R.layout.popup,null, false),300,100,true);
// RelativeLayout01 is Main Activity Root Layout
popupWindow.showAtLocation(findViewById(R.id.relativelayout), Gravity.CENTER, 0,0);
} else
{
Chronometer chrono=(Chronometer)findViewById(R.id.chronometer);
chrono.start();
}
}
public void onNothingSelected(AdapterView<?> arg0) {}
});
}
can any help to me
final String[] items = {"A", "B", "C"};
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose me!");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if ("A".equals(items[item]) || "B".equals(items[item])) {
// run whatever...
}
if ("C".equals(items[item])) {
final EditText edit = new EditText(context);
final Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose a custom option.");
builder.setView(edit);
builder.setPositiveButton("Save", new OnClickListener() {
public void onClick(final DialogInterface dialog, final int which) {
String input = edit.getText().toString();
// add input to array, or do whatever.
dialog.dismiss();
}
});
builder.create().show();
}
dialog.dismiss();
}
});
builder.create().show();
I didn't test it (written straight from my mind), but it should work with a few modifications.
Good luck
Tom
TRy this code..
public class Starttracker extends Activity {
String[] Items = {
"A",
"B",
"C",
"D",
};
Spinner s1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start);
s1 = (Spinner) findViewById(R.id.spinner);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this,android.R.layout.simple_spinner_item,Items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(adapter);
}
public boolean onItemSelected(AdapterView parent,View v, int position, long id) {
if (((items[position])=="A")||((items[position])=="B")) {
Chronometer chrono=(Chronometer)findViewById(R.id.chronometer);
chrono.start();
}
}
//.....
GoodLuck
the answer is following to my question:
{
int size=tempArray.length;
for(int i=0;i<size;i++){
Items.add(tempArray[i]);
}
and
if(index==3)
{
final Dialog dialog=new Dialog(Starttracker.this);
dialog.setContentView(R.layout.popup);
dialog.setTitle("Enter The Item");
dialog.setCanceledOnTouchOutside(true);
final EditText filename=(EditText)dialog.findViewById(R.id.filename);
filename.setText("");
Button d_ok=(Button)dialog.findViewById(R.id.d_ok);
Button d_cancel=(Button)dialog.findViewById(R.id.d_cancel);
d_ok.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
// TODO Auto-generated method stub
String textHolder = filename.getText().toString();
dialog.dismiss();
Items.add(textHolder);
// s1.setAdapter(adapter);
// notifyDataSetChanged();
}
});
d_cancel.setOnTouchListener(new OnTouchListener(){
public boolean onTouch(View v,MotionEvent me){
dialog.dismiss();
return false;
}
});
dialog.show();
return;
}
thank a lot to all
Shameless plug for my project.
Check out Android Popup Spinner View

Categories

Resources