Get value from Android listview and put it in extra - android-listview

In my code below I created a method which is: I would like to put a variable in putExtra that I can get it in the new activity. The problem is in the new activity gave me the first value(numtelephone) from first element in my list. I know that because of getItem(0), but how can I get the value( numtelephone ) for every element from the list?
public class ListClient extends Activity {
String myJSON,test;
TextView numt;
private static final String TAG_RESULTS="result";
private static final String TAG_NOMCLIENT = "nomclient";
private static String TAG_NUMTELEPHONE ="numtelephone";
private static final String TAG_DEPART ="depart";
private static final String TAG_DESTINATION ="destination";
private static final String TAG_NBRPERSONNE ="nbrpersonne";
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
ListView list;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_client);
list = (ListView) findViewById(R.id.list);
personList = new ArrayList<HashMap<String,String>>();
getData();
}
protected void showList(){
//json parsing etc...
ListAdapter adapter = new SimpleAdapter(
ListClient.this, personList, R.layout.list_item,
new String[]{TAG_NOMCLIENT,TAG_NUMTELEPHONE,TAG_DEPART,TAG_DEPART,TAG_NBRPERSONNE},
new int[]{R.id.name, R.id.numt, R.id.depart, R.id.destination, R.id.nbrpersonne}
);
list.setAdapter(adapter);
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
// json dowload from web, not needed in this question
return "";
}
#Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
public void GoUpdate(View v ) {
Intent in = new Intent(getBaseContext(), Update.class);
in.putExtra("NUMTELEPHONE",((HashMap<String, String>)list.getAdapter().getItem(0)).get("numtelephone"));
}
startActivity(in);
}
}

There is simple and only one solution. Delete your xml android:click property of list and add this list#setOnItemClickListener in your onCreate:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_client);
list = (ListView) findViewById(R.id.list);
personList = new ArrayList<HashMap<String,String>>();
getData();
//this thing has been added
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(id!=-1){
Intent in = new Intent(getBaseContext(), Update.class);
in.putExtra("NUMTELEPHONE", ((HashMap<String, String>) list.getAdapter().getItem((int)id)).get("numtelephone")); //TAG_NUMTELEPHONE
startActivity(in);
}
}
});
}
To move it from onCreate do:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_client);
list = (ListView) findViewById(R.id.list);
personList = new ArrayList<HashMap<String, String>>();
getData();
list.setOnItemClickListener(new OnMyListItemClickListener());
}
Context context = this;
private class OnMyListItemClickListener implements AdapterView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(id!=-1){
Intent in = new Intent(context, Update.class);
in.putExtra("NUMTELEPHONE", ((HashMap<String, String>) list.getAdapter().getItem((int) id)).get("numtelephone")); //TAG_NUMTELEPHONE
startActivity(in);
}
}
}
Lesson learned - dont create sucha buttons - they are not aware in which item they are, so you cant extract the id - instead just use something like AlertDialog
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(id!=-1){
AlertDialog.Builder al = new AlertDialog.Builder(context);
al.setMessage("Are you sure you want to do it?");
al.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent in = new Intent(context, Update.class);
in.putExtra("NUMTELEPHONE", ((HashMap<String, String>) list.getAdapter().getItem((int) id)).get(TAG_NUMTELEPHONE));
startActivity(in);
}
});
al.setNegativeButton(android.R.string.no, null);
al.show();
}
}

Related

com.google.firebase.database.DatabaseException: Can't convert object of type java.util.ArrayList to type

public class MainActivity extends AppCompatActivity {
DatabaseReference myRef;
PlayersAdapter adapter;
RecyclerView recyclerView;
private static ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.tvplayers);
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
progressDialog.setMessage("Loading");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setProgress(0);
// Read from the database
myRef = FirebaseDatabase.getInstance().getReference("player");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
// String value = dataSnapshot.getValue(String.class);
progressDialog.show();
ArrayList<PlayerModal> array= new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
// PlayerModal displayProducts = ds.getValue(PlayerModal.class);
PlayerModal value = dataSnapshot.getValue(PlayerModal.class);
array.add(value);
progressDialog.dismiss();
}
adapter= new PlayersAdapter(MainActivity.this,array);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
//
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
}
}

Passing Text From Listview to another Activity when I click action item of the listview

I have a listview in my main activity.In each row i have a image view,when i click that image view QuickAction(Like popover in ios) will appears.My request is, I want to setText the text from listview to the another Activity's edittext when i click the action item in the quick action.Please help..
Here is my Main Activity
public class ExampleActivity extends Activity {
private static final int ID_UP = 1;
private static final int ID_DOWN = 2;
private static final int ID_SEARCH = 3;
private static final int ID_INFO = 4;
private QuickAction quickAction;
private ActionItem nextItem;
private ActionItem prevItem;
private ActionItem searchItem;
private ListView view;
private ContactsAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
view = (ListView) findViewById(R.id.listView1);
final Weather weather_data[] = new Weather[] { new Weather(R.drawable.icon, "Cloudy"),
new Weather(R.drawable.icon, "Showers"),
new Weather(R.drawable.icon, "Snow"),
new Weather(R.drawable.icon, "Storm"),
new Weather(R.drawable.icon, "Sunny")
};
adapter = new ContactsAdapter(this, R.layout.main1,
weather_data);
}
void functiontorun(View view1) {
quickAction = new QuickAction(this,QuickAction.HORIZONTAL);
nextItem = new ActionItem(ID_DOWN, "Next", getResources().getDrawable(
R.drawable.menu_down_arrow));
prevItem = new ActionItem(ID_UP, "Prev", getResources().getDrawable(
R.drawable.menu_up_arrow));
searchItem = new ActionItem(ID_SEARCH, "Find", getResources()
.getDrawable(R.drawable.menu_search));
// use setSticky(true) to disable QuickAction dialog being dismissed
// after an item is clicked
prevItem.setSticky(true);
nextItem.setSticky(true);
// add action items into QuickAction
quickAction.addActionItem(nextItem);
quickAction.addActionItem(prevItem);
quickAction.addActionItem(searchItem);
// Set listener for action item clicked
final int position1 = view.getPositionForView(view1);
quickAction
.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
#Override
public void onItemClick(QuickAction source, int pos,
int actionId) {
ActionItem actionItem = quickAction.getActionItem(pos);
if (actionId == ID_SEARCH) {
Intent i=new Intent(ExampleActivity.this,Second.class);
i.putExtra("position",position1 );
Log.v("position","po" +position1);
startActivity(i);
} else if (actionId == ID_INFO) {
Toast.makeText(getApplicationContext(),
"I have no info this time",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),
actionItem.getTitle() + " selected",
Toast.LENGTH_SHORT).show();
}
}
});
quickAction.show(view1);
}
}
And my another activity
public class Second extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
EditText d1=(EditText) findViewById(R.id.editText1);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
final int position = (Integer) bundle.get("position");
Log.v("position","po1 " +position);
ArrayList<Weather> array = new ArrayList<Weather>();
Log.v("position","po1 " +array);
}
}
}
contacts adapter:
public class ContactsAdapter extends ArrayAdapter{
Context context;
int layoutResourceId;
Weather data[] = null;
public ContactsAdapter(Context context, int layoutResourceId, Weather[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
WeatherHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new WeatherHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.imageView1);
holder.imgIcon.findViewById(R.id.imageView1).setOnClickListener(mBuyButtonClickListener);
holder.txtTitle = (TextView)row.findViewById(R.id.textView1);
//((ImageView) row.findViewById(R.id.im)).setOnClickListener(mBuyButtonClickListener);
row.setTag(holder);
}
else
{
holder = (WeatherHolder)row.getTag();
}
Weather weather = data[position];
holder.txtTitle.setText(weather.title);
holder.imgIcon.setImageResource(weather.icon);
return row;
}
static class WeatherHolder
{
ImageView imgIcon;
TextView txtTitle;
}
private OnClickListener mBuyButtonClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
((ExampleActivity) context).functiontorun(v);
}
};
}
private OnClickListener mBuyButtonClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
WeatherHolder holder = (WeatherHolder) v.getTag;
String string = holder.txtTitle .getText();
((ExampleActivity) context).functiontorun(string);
}
};
just pass the string to your activity and change the parameter of the functiontorun as string

Refresh ListView when Device receives GCM IntentService Message

My app is able to receive messages from GCM and saves the messages to the SQLlite database on the phone. The messages are viewable in a activity that has a listview.
In the code below, the onPause() function refreshes the listView. This is not a good implementation because it only works if the activity is not displayed at the time of the update. If the activity is displayed at the time of an update, the list is static and does not update.
Questions:
How to I update the listview when the activity is being displayed? Or is there a way to use a background service to update the adapter, so that whenever the activity is displayed, it always shows the newest data.
is this kind of functionality currently not possible with android and I'll need to implement something else like 'pull-to-refresh'?
refreshing listview in OnResume() crashes the application, and shows a null pointer exception.
Activity:
public class NotesView extends Activity implements OnItemClickListener {
ListView listView;
NoteAdapter objAdapter;
NotificationsDatabase db = new NotificationsDatabase(this);
List<Notes> listAlerts;
String note;
String time;
TextView noteView;
TextView timeView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note);
listView = (ListView) findViewById(R.id.notelist);
listView.setOnItemClickListener(this);
noteView = (TextView) findViewById(R.id.noteDisplay);
timeView = (TextView) findViewById(R.id.notetimeStampDisplay);
new MyTask().execute();
}
// My AsyncTask start...
class MyTask extends AsyncTask<Void, Void, List<Notes>> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NotesView.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
if (isCancelled()) {
this.cancel(true);
}
}
#Override
protected List<Notes> doInBackground(Void... params) {
db.open();
listAlerts = db.getData();
if (isCancelled()) {
this.cancel(true);
}
return null;
}
protected void onPostExecute(List<Notes> alerts) {
if (null != pDialog && pDialog.isShowing()) {
pDialog.dismiss();
}
db.close();
setAdapterToListview();
}
}// end myTask
public void setAdapterToListview() {
objAdapter = new NoteAdapter(NotesView.this, R.layout.row_notes, listAlerts);
objAdapter.sortByNoteDesc();
objAdapter.notifyDataSetChanged();
listView.setAdapter(objAdapter);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
Intent intent = new Intent(
NotesView.this.getApplicationContext(),
TabBarExample.class);
intent.putExtra("goToTab", "Alerts");
startActivity(intent);
return true;
}
return super.onKeyDown(keyCode, event);
}
public void onItemClick(AdapterView<?> parent, View viewDel, int position,
long id) {
for (int i = 0; i < 1; i++) {
Notes item = listAlerts.get(position);
int ids = item.getId();
note = item.getNote();
time = item.getTimeStamp();
}
System.out.println(note + " " + time);
//
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
setContentView(R.layout.note);
listView = (ListView) findViewById(R.id.notelist);
listView.setAdapter(null);
listView.setOnItemClickListener(this);
noteView = (TextView) findViewById(R.id.noteDisplay);
timeView = (TextView) findViewById(R.id.notetimeStampDisplay);
new MyTask().execute();
}
#Override
protected void onDestroy() {
}
}
Code snippets From GCMIntentService
#Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message");
//String message = getString(R.string.gcm_message);
System.out.println("onMessage: ");
Bundle extras = intent.getExtras();
String message = extras.getString("message");
String event_id_from_server = extras.getString("server_id");
// displayMessage(context, message);
generateNotification(context, message);
saveMsg(message);
System.out.println("server id is " + event_id_from_server);
if (event_id_from_server != null) {
updateLocalDatabase(event_id_from_server);
}
}
public void saveMsg(String msg) {
boolean worked = true;
try {
NotificationsDatabase entry = new NotificationsDatabase(GCMIntentService.this);
entry.open();
java.util.Date date = new java.util.Date();
Timestamp x = new Timestamp(date.getTime());
String timeStamp = x.toLocaleString();
entry.createEntry(msg, timeStamp);
entry.close();
//update adapter service
} catch (Exception e) {
worked = false;
String error = e.toString();
System.out.println(error);
} finally {
if (worked) {
}
}
}
I cleaned up your code a little bit. Basically all the view assignments should be done once in onCreate, while the loading of the data should be done in onResume(). See if this helps:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note);
listView = (ListView) findViewById(R.id.notelist);
listView.setAdapter(null);
listView.setOnItemClickListener(this);
noteView = (TextView) findViewById(R.id.noteDisplay);
timeView = (TextView) findViewById(R.id.notetimeStampDisplay);
}
#Override
protected void onResume() {
super.onResume();
new MyTask().execute();
}
#Override
protected void onPause() {
super.onPause();
}

setOnItemClickListener in customized listview

Here is the activity ShowData.java where i am setting up customized listview.. Now i need to click view on that listview and need to display another activity but throws force close.. It throws error on listview.setAdapter(adapter);
public class ShowData extends Activity
{
ListView listview;
Intent intent;
ArrayList<BeanClass> datalist;
CustomAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
listview = (ListView) findViewById(R.id.listView1);
Intent intent = getIntent();
datalist = (ArrayList<BeanClass>) intent.getSerializableExtra("list");
Log.i("Size of ArrayList", "is " +datalist.size());
adapter = new CustomAdapter(ShowData.this, R.layout.customrow , datalist);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3)
{
Intent i = new Intent(ShowData.this,DetailActivity.class);
i.putExtra("datalist", datalist);
i.putExtra("position", arg2);
startActivity(i);
}
}
}
Here is the CustomAdapter.java
public class CustomAdapter extends ArrayAdapter<BeanClass>
{
Context context;
int layoutResourceId;
BeanClass bc;
ArrayList<BeanClass> vbc;
public CustomAdapter(Context context, int layoutResourceId, ArrayList<BeanClass> vbc)
{
super(context, layoutResourceId, vbc);
this.context=context;
this.layoutResourceId=layoutResourceId;
this.vbc=vbc;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
StringReaderHolder holder;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent,false);
holder= new StringReaderHolder();
holder.mytext1 = (TextView) row.findViewById(R.id.textView1);
holder.mytext2 = (TextView) row.findViewById(R.id.textView2);
holder.mytext3 = (TextView) row.findViewById(R.id.textView3);
row.setTag(holder);
}
else
{
holder = (StringReaderHolder) row.getTag();
}
BeanClass bsObject = vbc.get(position);
holder.mytext1.setText(bsObject.name);
holder.mytext2.setText(bsObject.address);
holder.mytext3.setText(bsObject.phone);
return row;
}
static class StringReaderHolder
{
TextView mytext1,mytext2,mytext3;
}
}
How should i use setOnItemClickListener...??? Thanks...
In Your getView Method try:
row.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(context,DetailActivity.class);
i.putExtra("datalist", vbc);
i.putExtra("position", position);
startActivity(i);
}
});

What's the problems when I use ".getText().toString();"

#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText nameText = (EditText) findViewById(R.id.editText1);
name = nameText.getText().toString();
nameText.setText("");
EditText numberText = (EditText) findViewById(R.id.editText2);
number = numberText.getText().toString();
numberText.setText("");
person = new Person(name, number);
order.add(person);
PersonAdapter pa = new PersonAdapter(con, R.layout.row, order);
setListAdapter(pa);
}
});
}
#Override
protected void onListItemClick(ListView l, View v, final int position, long id) {
// TODO Auto-generated method stub
final int index = position;
AlertDialog.Builder aDialog = new AlertDialog.Builder(this);
aDialog.setTitle("What do you want??");
aDialog.setPositiveButton("Delete",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
order.remove(index);
PersonAdapter pa = new PersonAdapter(con, R.layout.row,
order);
setListAdapter(pa);
}
});
aDialog.setNeutralButton("Edit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) con.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_dialog, (ViewGroup)findViewById(R.id.root_layout));
builder = new AlertDialog.Builder(con);
builder.setView(layout);
builder.setTitle("Fill EditText");
builder.setIcon(R.drawable.icon);
editNum = (EditText)findViewById(R.id.editNum);
editName = (EditText)findViewById(R.id.editName);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
name = editName.getText().toString();
number = editNum.getText().toString();
order.set(position, new Person(name,number));
PersonAdapter pa = new PersonAdapter(con, R.layout.row, order);
setListAdapter(pa);
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
alertDialog = builder.create();
alertDialog.show();
}
});
aDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
AlertDialog ad = aDialog.create();
ad.show();
}
public PersonAdapter(Context context, int textViewResourceId,
ArrayList<Person> items) {
super(context, textViewResourceId, items);
this.items = items;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.row, null);
}
Person p = items.get(position);
if (p != null) {
TextView tt = (TextView) v.findViewById(R.id.android_toptext);
TextView bt = (TextView) v.findViewById(R.id.android_bottomtext);
if (tt != null) {
tt.setText(p.getName());
}
if (bt != null) {
bt.setText("TEL : " + p.getNumber());
}
}
return v;
}
private String name;
private String number;
public Person(String name, String number) {
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
public String getNumber() {
return number;
}
}
I am practicing Widget(exactly I am making custom dialog) and Listener In android . But I stop now because ".getText().toString();" makes error ... I can't understand.. T^T Please Help me... why it makes error?? I think It doesn't have problem
You should declare your EditText globally
EditText editName;
EditText editNum;
#Override
public void onCreate(Bundle savedInstanceState) {
...
}
.....
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) con.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_dialog, (ViewGroup)findViewById(R.id.root_layout));
builder = new AlertDialog.Builder(con);
builder.setView(layout);
builder.setTitle("Fill EditText modificated");
builder.setIcon(R.drawable.icon);
editName = (EditText)findViewById(R.id.editName);
editNum = (EditText)findViewById(R.id.editNum);