custom list view passing multiple data to next activity - android

i have done custom listview
it has 6 textview and 1 image view in each row
whati did is when press on item it just goes to my second activity
but what it want is to pass the items of the row to the second activity
i don't know how to do it or where to add it in the list or in the adapter
also what to do in the second activity
here is my first activity
public class ImageListActivity extends AppCompatActivity {
private DatabaseReference mDatabaseRef;
private List<ImageUpload> imgList;
private ListView lv;
private ImageListAdapter adapter;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_list);
imgList = new ArrayList<>();
lv = (ListView) findViewById(R.id.listViewImage);
//Show progress dialog during list image loading
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Please wait loading list image...");
progressDialog.show();
mDatabaseRef = FirebaseDatabase.getInstance().getReference(ListActivity.FB_Database_Path);
mDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
progressDialog.dismiss();
//Fetch image data from firebase database
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
//ImageUpload class require default constructor
ImageUpload img = snapshot.getValue(ImageUpload.class);
imgList.add(img);
}
//Init adapter
adapter = new ImageListAdapter(ImageListActivity.this, R.layout.image_item, imgList);
//Set adapter for listview
lv.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
progressDialog.dismiss();
}
});
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent myintent = new Intent(view.getContext(), Buy1Activity.class);
startActivityForResult(myintent, 0);
}
});
}
}
and this is adapter
public class ImageListAdapter extends ArrayAdapter<ImageUpload> {
private Activity context;
private int resource;
private List<ImageUpload> listImage;
public ImageListAdapter(#NonNull Activity context, #LayoutRes int resource, #NonNull List<ImageUpload> objects) {
super(context, resource, objects);
this.context = context;
this.resource = resource;
listImage = objects;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View v = inflater.inflate(resource, null);
TextView tvName = (TextView) v.findViewById(R.id.tvImageName);
TextView tvModel = (TextView) v.findViewById(R.id.tvImageModel);
TextView tvBrand = (TextView) v.findViewById(R.id.tvImageBrand);
TextView tvPrice = (TextView) v.findViewById(R.id.tvImagePrice);
TextView tvyear = (TextView) v.findViewById(R.id.tvImageYear);
TextView tvDesc = (TextView) v.findViewById(R.id.tvImageDesc);
ImageView img = (ImageView) v.findViewById(R.id.imgView);
tvModel.setText(listImage.get(position).getModel());
tvName.setText(listImage.get(position).getName());
tvBrand.setText(listImage.get(position).getBrand());
tvyear.setText(listImage.get(position).getYear());
tvDesc.setText(listImage.get(position).getDesc());
tvPrice.setText(listImage.get(position).getPrice());
Glide.with(context).load(listImage.get(position).getUrl()).into(img);
return v;
}
}

What I understand, you want to transfer the entire object namely ImageUpload of the list item you clicked on. For this you can create ImageUpload model class as Parcelable and and then pass selected ImageUpload object in your intent and retrieve it back from Intent using getParcelable().
on list item click:
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent myintent = new Intent(view.getContext(), Buy1Activity.class);
myintent.putExtra("selected_image_upload", ((ImageUpload) adapter.getItem(position)));
startActivityForResult(myintent, 0);
}
});
on Buy1Activity, to get the selected ImageUpload object in onCreate():
ImageUpload imgUploadObj = getIntent().getExtras().getParcelable("selected_image_upload");
You can get hint from here to create a class Parcelable.

Try this
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ImageUpload img = adapter.get(position);
Intent myintent = new Intent(view.getContext(), Buy1Activity.class);
myintent.putParcelableArrayListExtra("parcel_data", img);
startActivityForResult(myintent, 0);
}
});
In your Buy1Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
ImageUpload img = (ImageUpload) getIntent().getParcelableArrayListExtra("parcel_data");
}
Hope it help!

Related

How can I sort the listview by nearest location to the current location?

I am going to sort the list of my location from firebase. The list should be arrange from the nearest location with current location.
How can I sort the listview by nearest location to the current location?
This is my adapter
public class AdminImageListAdapter extends ArrayAdapter <AdminImageUpload> {
private Activity context;
private int resource;
private List<AdminImageUpload> adlistImage;
public AdminImageListAdapter(#NonNull Activity context, #LayoutRes int resource, #NonNull List<AdminImageUpload> objects) {
super(context, resource, objects);
this.context = context;
this.resource = resource;
adlistImage = objects;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View v = inflater.inflate(resource, null);
TextView adName = (TextView) v.findViewById(adImageName);
TextView adAddress = (TextView) v.findViewById(adImageAddress);
ImageView img = (ImageView) v.findViewById(R.id.adimgView);
adName.setText(adlistImage.get(position).getName());
adAddress.setText(adlistImage.get(position).getAddress());
Glide.with(context).load(adlistImage.get(position).getUrl()).into(img);
return v;
}
This is my Listview
public class AirConditioningActivity extends AppCompatActivity {
private DatabaseReference mDatabaseRef;
private List<AdminImageUpload> adimgList;
private ListView lvl;
private AdminImageListAdapter adapter;
private ProgressDialog progressDialog;
private FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_air_conditioning);
adimgList = new ArrayList<>();
lvl= (ListView) findViewById(R.id.listViewImage);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Please wait loading list image...");
progressDialog.show();
firebaseAuth = FirebaseAuth.getInstance();
mDatabaseRef = FirebaseDatabase.getInstance().getReference(AdminKeyWorkshopsActivity.FB_DATABASE_PATH);
Query mQuery = mDatabaseRef.orderByChild("category").equalTo("AIR-CONDITIONING");
mQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
progressDialog.dismiss();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
AdminImageUpload image = snapshot.getValue(AdminImageUpload.class);
adimgList.add(image);
}
adapter = new AdminImageListAdapter(AirConditioningActivity.this, R.layout.admin_image_item, adimgList);
lvl.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
progressDialog.dismiss();
}
});
lvl.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
AdminImageUpload adimgList = (AdminImageUpload) adapterView.getAdapter().getItem(i);
Intent intent = new Intent(AirConditioningActivity.this, AdminDetailsOfWorkshops.class);
String name = adimgList.getName();
String address = adimgList.getAddress();
String contact = adimgList.getContact();
String category = adimgList.getCategory();
String url = adimgList.getUrl();
intent.putExtra("name", name);
intent.putExtra("address", address);
intent.putExtra("contact", contact);
intent.putExtra("category", category);
intent.putExtra("URL", url);
startActivity(intent);
}
});
}
you can use the float distanceTo method and then use
Collection.sort on the results to get the nearest distance.

How to show id and name in toast after clicking per button

I am unable to Toast every id and name after clicking button. Every time last id and name are showing after clicking different button. I want to show every list of data in Toast after clicking specific button
Activity
public class ListViewActivity extends AppCompatActivity {
ListView studentListView;
ArrayList<Student> studentList = new ArrayList<>();
StudentAdapter studentAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
studentListView = (ListView) findViewById(R.id.studentListView);
studentList.add(new Student(01, "Monir"));
studentList.add(new Student(02, "Jibon"));
studentList.add(new Student(03, "Mahmud"));
studentList.add(new Student(04, "Saiful"));
studentList.add(new Student(05, "Arif"));
studentAdapter = new StudentAdapter(this, studentList);
studentListView.setAdapter(studentAdapter);
}
public void viewStudentClick(View view) {
Toast.makeText(getApplicationContext(),studentAdapter.nameText.getText(), Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),studentAdapter.idText.getText(), Toast.LENGTH_SHORT).show();
}
}
Adapter
public class StudentAdapter extends ArrayAdapter<Student> {
private Activity context;
private ArrayList<Student> students;
TextView idText;
TextView nameText;
public StudentAdapter(Activity context, ArrayList<Student> student) {
super(context, R.layout.student_info, student);
this.context = context;
this.students = student;
}
//Array Adapter
public View getView(int position, View rowView, ViewGroup parent){
LayoutInflater layoutInflater = context.getLayoutInflater();
rowView = layoutInflater.inflate(R.layout.student_info, parent, false);
idText = (TextView) rowView.findViewById(R.id.idText);
nameText = (TextView) rowView.findViewById(R.id.nameText);
idText.setText(students.get(position).getId()+"");
nameText.setText(String.valueOf(students.get(position).getName()));
return rowView;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
studentListView = (ListView) findViewById(R.id.studentListView);
studentList.add(new Student(01, "Monir"));
studentList.add(new Student(02, "Jibon"));
studentList.add(new Student(03, "Mahmud"));
studentList.add(new Student(04, "Saiful"));
studentList.add(new Student(05, "Arif"));
studentAdapter = new StudentAdapter(this, studentList);
studentListView.setAdapter(studentAdapter);
studentListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(ListViewActivity.this,studentList.get(position).getId() +
studentList.get(position).getName(),Toast.LENGTH_SHORT).show();
}
});
}
Use :
studentListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// selected item
String name = (String) parent.getItemAtPosition(position);
Toast toast = Toast.makeText(getApplicationContext(),"Position:"+position+", Name: "+name, Toast.LENGTH_SHORT).show();
}
});

Parse.com onListItemClick not displaying any detail information

I am trying out this code i have that uses Parse.com to get restaurant names and put the in a listView.
When you click on one of the names then it takes you to a details page where you can get detail information about the restaurant.
Problem is when i click on the name on the ListView it goes to the details pages but displays nothing.
I am new to android and parse and don't fully understand how it should work.
here is the code in my mainActivity
public class MainActivity extends Activity {
private CustomAdapter urgentTodosAdapter;
private ParseQueryAdapter<ParseObject> mainAdapter;
private ListView listView;
List<ParseObject> Name =new ArrayList<ParseObject>();
#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 AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
// Send single item click data to SingleItemView Class
Intent random1 = new Intent(MainActivity.this, SingleItemView.class);
if (Name.size() > i)
// Pass data "name" followed by the position
random1.putExtra("Name", Name.get(i).getString("Name"));
// Open SingleItemView.java Activity
startActivity(random1);
}
});
}
}
and my customAdapter class
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;
}
}
and the class that suppose to display the name of the restaurant etc.
#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
// Load the text into the TextView
txtname.setText(Name);
}
}
Please see my comment in the OP's comment section to get some context:
Answer:
In your MainActivity you didn't create a query to add to the adapter. Take a look below and adjust the ParseQuery to your needs:
MainActivity Class
public class MainActivity extends Activity {
private CustomAdapter urgentTodosAdapter;
private ParseQueryAdapter<ParseObject> mainAdapter;
private ListView listView;
List<ParseObject> Name =new ArrayList<ParseObject>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
listView = (ListView) findViewById(R.id.listView1);
//I'm not sure how you initialized your custom adapter - i'll show you how i did it, but yours might work too
urgentTodosAdapter = new urgentTodosAdapter(MainActivity.this, new ArrayList<RestaurantDetail>());
listView.setAdapter(urgentTodosAdapter);
//Here is where you forgot to add your ParseQuery for 'Restaurants'
ParseQuery<RestaurantDetail> query = ParseQuery.getQuery(RestaurantDetail.class);
query.findInBackground(new FindCallback<RestaurantDetail>() {
public void done(List<RestaurantDetail> resutarantList, ParseException e) {
if (e == null) {
if (resutarantList.size() > 0) {
for (int i = 0; i < resutarantList.size(); i++) {
//you forgot to do this - didn't add anything for the adapter to show.
urgentTodosAdapter.add(resutarantList.get(i));
}
} else {
// do something if empty
}
} else {
// do something if null
}
}
});
//This is fine here, but you can also do the same in your adapter class; I'll keep this here and show you where to put it
//in the adapter as well.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
// Send single item click data to SingleItemView Class
Intent random1 = new Intent(MainActivity.this, SingleItemView.class);
if (Name.size() > i)
// Pass data "name" followed by the position
random1.putExtra("Name", Name.get(i).getString("Name"));
// Open SingleItemView.java Activity
startActivity(random1);
}
});
}
}
CustomAdapter class:
public class CustomAdapter extends ArrayAdapter<RestaurantDetail> {
private final Context mContext;
private List<RestaurantDetail> restrauants;
public CustomAdapter(Context context, List<RestaurantDetail> objects) {
super(context, R.layout.include_restaurants, objects);
this.mContext = context;
this.restrauants = objects;
}
public View getView(final int position, View convertView, final ViewGroup parent) {
if (convertView == null) {
LayoutInflater mLayoutInflater = LayoutInflater.from(mContext);
v = mLayoutInflater.inflate(R.layout.include_restaurants, null);
}
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"));
//this is also where you can handle to onClick stuff
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return v;
}
}
Initialize your parse class: this is also where you can put your getters/setters.
#ParseClassName("YourClassNameInYourDBHere")
public class ResuaurantDetail(your class here) extends ParseObject
{
}

Adding dynamic items to listview

Hi I want to add an item to a listview.
This is my New message activity in which I wan to pass an item to my Main Activity. I'm not quite sure how to pass this data through an intent any help would be greatly appreciated.
public class NewMessage extends ActionBarActivity {
EditText new_message;
Button post_new_message_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_message);
new_message = (EditText) findViewById(R.id.message_content);
post_new_message_button = (Button) findViewById(R.id.message_send);
post_new_message_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView username = (TextView) findViewById(R.id.conversation_username2);
itemAdapter.add(new MessageItem(1656,"Bill Smith", "image", DateTime.now(), new_message.getText().toString()));
itemAdapter.notifyDataSetChanged();
if (v.getId() == R.id.message_send);
new_message.setText("");
}
});
}
}
This is my main activity I want to pass in the data
public class MainActivity extends ActionBarActivity {
TextView threadId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button newMessage = (Button) findViewById(R.id.new_message_button);
newMessage.setOnClickListener (new View.OnClickListener(){
#Override
public void onClick(View v){
Intent newMessage = new Intent(MainActivity.this, NewMessage.class);
startActivity(newMessage);
}
});
final ListView listView = (ListView) this.findViewById(R.id.messagingListView);
final ActivityAdapter itemAdapter = new ActivityAdapter(getApplicationContext(), this.MessageFeedData());
listView.setAdapter(itemAdapter);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
listView.getAdapter().getItem(position);
}
});
}
// Get dummy data for Activity Feed
public ArrayList<MessageItem> MessageFeedData() {
ArrayList<MessageItem> items = new ArrayList<MessageItem>();
items.add(new MessageItem(1, "Bob Doe", "image", DateTime.now(), "Hello how are you?"));
items.add(new MessageItem(200, "John Smith", "image", DateTime.now(), "Hello what are you doing"));
return items;
}
class ActivityFeedTask extends AsyncTask<Integer, Void, Void> {
ArrayList<MessageItem> recentTracks;
}
public class ActivityAdapter extends ArrayAdapter<MessageItem> {
private final Context context;
private final ArrayList<MessageItem> items;
//private int currentPage = 0;
public ActivityAdapter(Context context, ArrayList<MessageItem> recentTrackArrayList) {
super(context, 0, recentTrackArrayList);
this.context = context;
this.items = recentTrackArrayList;
}
public View getView(int position, View convertView, ViewGroup parent) {
View rowView;
{
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = getLayoutInflater().inflate
(R.layout.message_list_item, parent, false);
//final MessageItem item = items.get(position);
rowView = convertView;
TextView comment2 = (TextView) rowView
.findViewById(R.id.messaging_username);
comment2.setText(items.get(position).Username);
ImageView comment3 = (ImageView) rowView
.findViewById(R.id.messaging_photo);
if (items.get(position).Image == null) {
comment3.setImageResource(R.drawable.ic_launcher);
}
TextView comment4 = (TextView) rowView
.findViewById(R.id.messaging_date);
comment4.setText(items.get(position).DateTimeStamp.toString());
TextView comment5 = (TextView) rowView
.findViewById(R.id.messaging_string);
comment5.setText(items.get(position).MessageString);
}
return convertView;
}
}
}
if you just want to pass data back and forth between the two activities, maybe you should use:
startActivityForResult(Intent intent, int requestCode)
and
onActivityResult(int requestCode, int resultCode, Intent data)
So that when the NewMessageActivity finishes, it can send the data back to the main activity.

List items parse displaying the same String onClick (PutExtra)

I am trying to transfer my username value to a new activity. However when I do this it is displaying the first array item I have added, for example the code below displays "Bob Jones" for the username in the Conversation activity even if I click on a different item in the list.
public class MainActivity extends Activity {
TextView user;
TextView threadId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//messaging_string = (TextView) findViewById(R.id.messaging_string);
//this.GetActivityFeedData();
final ListView listView = (ListView) this.findViewById(R.id.messagingListView);
final ActivityAdapter itemAdapter = new ActivityAdapter(getApplicationContext(), this.GetActivityFeedData());
listView.setAdapter(itemAdapter);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
user = (TextView) findViewById(R.id.messaging_username);
threadId = (TextView) findViewById(R.id.messaging_threadId);
listView.getAdapter().getItem(position);
Intent intent = new Intent(MainActivity.this, ConversationView.class);
intent.putExtra("username", user.getText().toString());
intent.putExtra("pos", position);
intent.putExtra("threadId", threadId.getText().toString());
startActivity(intent);
}
});
}
public ArrayList<MessageItem> GetActivityFeedData() {
ArrayList<MessageItem> items = new ArrayList<MessageItem>();
items.add(new MessageItem(6, "Lorna Smith", "image", DateTime.now(), "Hello what are you doing"));
return items;
}
class ActivityFeedTask extends AsyncTask<Integer, Void, Void> {
ArrayList<MessageItem> recentTracks;
//remove to not loading more data
}
public class ActivityAdapter extends ArrayAdapter<MessageItem> {
private final Context context;
private final ArrayList<MessageItem> items;
private int currentPage = 0;
public ActivityAdapter(Context context, ArrayList<MessageItem> recentTrackArrayList) {
super(context, 0, recentTrackArrayList);
this.context = context;
this.items = recentTrackArrayList;
}
}
you have to fetch the content of the row you clicked. You can retrieve this object with parent.getItemAtPosition(position);,
MessageItem itemAtPostion = (MessageItem) parent.getItemAtPosition(position);
Intent intent = new Intent(MainActivity.this, ConversationView.class);
intent.putExtra("username", itemAtPostion.Username);
intent.putExtra("pos", position);
intent.putExtra("threadId", itemAtPostion.ThreadId);

Categories

Resources