getItemIdAtPosition() in listview not showing - java

I need to get getItemIdAtPosition() from listView to get the id of the records from sqlite database. When i click on the listView on any item, it always shows "null" not showing the id.
this is the code:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
int id= ((int) listView.getItemIdAtPosition(i));
//create our intent, as per usual
Intent intent=new Intent(Tutorial10.this, Activity2.class);
intent.putExtra(ID_EXTRA, id);
startActivity(intent);
}
});
This activity2.java
public class Activity2 extends Activity{
String passedVar=null;
private TextView passedView=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act2);
//Get our passed variable from our intent's EXTRAS
passedVar=getIntent().getStringExtra(Tutorial10.ID_EXTRA);
//find out text view
passedView=(TextView)findViewById(R.id.passed);
//display our passed variable!!!
passedView.setText("YOU CLICKED ON="+passedVar);
}
}

You should change this line
int id= ((int) listView.getItemIdAtPosition(i));
with this
long id = adapterView.getItemIdAtPosition(i);
I hope this fixes your problem.

According to the Android official document here, there's no definition about the purpose of this function. It seems to call to getItemId() in Adapter, and getItemId() returns the value of Id in SQLite.
I guess you need to use SimpleCursorAdapter to work with the SQLite.

Related

How to pass data from a activity to a recycler view adapter in android

I'm trying to design a page where address are stored in recycler view -> cardview.
When the user clicks the add address button from the Activity A the user is navigated to the add address page in Activity B. Here the user can input customer name, address line 1 and address line two.
And once save button is clicked in Activity B, a cardview should be created under the add address button in the Activity A.
This design is just like the amazon mobile app add address option.
Could anyone give me an example hoe to pass the saved data from activity to recycler adapter. I know how to pass data from recycler adapter to activity with putExtra etc..
Kindly help me. Million Thanks in advance!
Code In Activity A(Where the Add address button is available and where the recycler view is present)
public class ProfileManageAdressFragment extends AppCompatActivity {
RecyclerView recyclerView;
ProfileManageAddressRecyclerAdapter adapter;
ArrayList<ProfileManageAddressGetterSetter> reviews;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_profile_manage_adress);
Button addAddress = findViewById(R.id.addNewAddress);
reviews = new ArrayList<>();
addAddress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Clicked", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(ProfileManageAdressFragment.this, AddNewAddress.class);
startActivity(intent);
}
});
}
}
Piece of Code that is responsible for adding a card view in Activity A. Kindly let me know how to invoke this below code on button click in Activity
reviews.add(new ProfileManageAddressGetterSetter("Customer Name", "address line 1", "address line 2"));
recyclerView = findViewById(R.id.addressRecyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(ProfileManageAdressFragment.this));
adapter = new ProfileManageAddressRecyclerAdapter(this, reviews);
recyclerView.setAdapter(adapter);
Code in the Recycler adapter
public class ProfileManageAddressRecyclerAdapter extends RecyclerView.Adapter<ProfileManageAddressRecyclerAdapter.ViewHolder> {
private ArrayList<ProfileManageAddressGetterSetter> mDataset = new ArrayList<>();
private Context context;
public static class ViewHolder extends RecyclerView.ViewHolder {
private TextView customer_name, address_one, address_two;
private Button edit, remove;
public ViewHolder(View v) {
super(v);
customer_name = (TextView) v.findViewById(R.id.customerName);
address_one = (TextView) v.findViewById(R.id.addressLineOne);
address_two = v.findViewById(R.id.addressLineTwo);
}
}
public ProfileManageAddressRecyclerAdapter(View.OnClickListener profileManageAdressFragment, ArrayList<ProfileManageAddressGetterSetter> dataset) {
mDataset.clear();
mDataset.addAll(dataset);
}
#Override
public ProfileManageAddressRecyclerAdapter.ViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_manage_address, parent, false);
ProfileManageAddressRecyclerAdapter.ViewHolder vh = new ProfileManageAddressRecyclerAdapter.ViewHolder(view);
return vh;
}
#Override
public void onBindViewHolder(#NonNull ProfileManageAddressRecyclerAdapter.ViewHolder holder, int position) {
ProfileManageAddressGetterSetter profileManageAddressGetterSetter = mDataset.get(position);
holder.address_one.setText(profileManageAddressGetterSetter.getAddress_line_1());
holder.address_two.setText(profileManageAddressGetterSetter.getGetAddress_line_2());
holder.customer_name.setText(profileManageAddressGetterSetter.getContractor_name());
}
#Override
public int getItemCount() {
return mDataset.size();
}
}
enter image description here - After trying the call from adapter using intent as mentioned above ended up with a 0.
Code in the Activity B
public class AddNewAddress extends AppCompatActivity {
private EditText customer_name, address_one, address_two;
private TextView cancel;
private Button add_address;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_new_address);
customer_name = findViewById(R.id.customerName);
address_one = findViewById(R.id.addressOne);
address_two = findViewById(R.id.addressTwo);
add_address = findViewById(R.id.addAddress);
cancel = findViewById(R.id.completeCancel);
String cancel_text = "Cancel";
SpannableString spanableObject = new SpannableString(cancel_text);
ClickableSpan clickableSpan = new ClickableSpan() {
#Override
public void onClick(View widget) {
Toast.makeText(AddNewAddress.this, "Clicked", Toast.LENGTH_SHORT).show();
}
#Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setColor(Color.BLUE);
}
};
spanableObject.setSpan(clickableSpan, 0, 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
cancel.setText(spanableObject);
cancel.setMovementMethod(LinkMovementMethod.getInstance());
final ProfileManageAdressFragment profileManageAdressFragment = new ProfileManageAdressFragment();
add_address.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AddNewAddress.this, ProfileManageAdressFragment.class);
startActivity(intent);
}
});
}
private void setFragment(android.support.v4.app.Fragment fragment) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_frame, fragment).commit();
}
}
Update 1:
Kindly check my updated Recycler adapter. When I run this 0 is displayed in the text area as shown in the attached image. I'm new to android. Kindly help with example.
I finally achieved my goal with the use of ActivityResult. Now I'm able to pass data from Activity to Cardview.
Solution: When button is clicked in Activity A, I start the activity with startResultActivity(). Later, when the Activity B i triggered. The end-user inputs the data and that data is passed with the use of putExtra() and once the save button is clicked in Activity B next setResult() in Activity B and finish().
Finally i define onActivityResult() in Activity A to get the result. Works well!!
I would create a global variable and then store all the data in that variable and simply just call that variable in adapter.
declare a global variable and assign null value to it:
public static String checking = null;
a then store data in when you need it:
checking = check.getText().toString();
then call it in your adapter class.
first make interface listener inside listener make function with parameter like this
interface YourRecycleViewClickListener {
fun onItemClickListener(param1:View, param2: String)
}
now extend your activity
class YourActivity:YourRecycleViewClickListener{
override fun onItemClickListener(param1:View, param2: String) {
//do any thing
}
}
third step make interface constract in your recycle adapter
class YourAdapter(
private val listener: YourRecycleViewClickListener){
holder.constraintLayout.setOnClickListener{
listener.onItemClickListener(param1,param2)
}
}
this is by kotlin lang
and by java is same but change syntax
that all to do

Creating different activities for each item in a ListActivity

How can I create a new activity when an item in my ListView is clicked? It would be best if I can create this in a single java file. Also, it would be great if someone explained how I can display text in the new activity, I may be wrong, but I assume I can somehow use TextView. Any thought would be helpful, thanks in advance!
Capture the item click event and create an intent that contains the data that you need to send the new activity. Then start the activity with your intent as normal.
YourActivity.java
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(YourActivity.this, YourNextActivity.class);
// Insert your logic to send data based on which item was clicked here
intent.putExtra("MY_EXTRA_DATA", "Some data!");
startActivity(intent);
}
});
In the activity you start, you can use getIntent() to retrieve the data you pass in.
YourNextActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
Intent intent = getIntent();
String data = intent.getStringExtra("MY_EXTRA_DATA");
TextView textView = (TextView) findViewById(R.id.yourId);
textView.setText(data);
}

how to set a text views text to an integer value of an object that was created from another class

the title is a bit confusing sorry about that i didnt know how to put it in words properly. I have a listView that uses an Adapter that i created myself. When the first row of the listView is pressed I have made it so it creates a new object from class called Ship that has 3 integer values. Below
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hangar);
ListAdapter adapter = new HangarAdapter(this, ship);
hangarList.setAdapter(adapter);
hangarList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Intent sendListEvents = new Intent();
if(position == 0)
{
Ship ship1 = new Ship();
ship1.setAddAmount(50);
ship1.setAddTime(5000);
ship1.setAddSpend(1000);
ship1.shipAdd();
}
}
}
In my adapter i have a textView called TextView2 and I want to set the text of it to ship1's value called addSpend. How do i do that.
if (position == 0) {
theImageView.setImageResource(R.drawable.planet);
TextView2.setText("This is where I want ship1's addSpend value to be displayed")
}
Well if I am correct then you have in the HangarAdapter class the object this (which references to the Activity in which you are right now: ListAdapter adapter = new HangarAdapter(this, ship);). Save this object to an variable (I call it MainActivity) in the HangarAdapter class .
Now you could just say in the HangarAdapter class: MainActivity.findViewById("TextBoxID").setText("MUHAHAHAH")

Item being selected automatically from spinner?

my issue is that whenever I add a lecture to the array list in the next activity, it calls back to this activity and updates it. However, for some reason onItemSelected is called right away as soon as I get back to the calling activity and I'm sent to the Lecture activity (the displayLectureIntent is started right away) as soon as I get back to the calling activity without even actually selecting anything from the spinner.
Could it be that as soon as I add something to the spinner, the spinner chooses the first object as default and therefore it "selects" it? Thanks
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_class_manager0);
Intent receivedIntent = getIntent();
if (receivedIntent.hasExtra("lectureManagerExtra")) {
lectureManager = (LectureManager) getIntent().getSerializableExtra("lectureManagerExtra");
update();
} else {
lectureManager = new LectureManager();
}
}
public void update() {
Spinner spinner = (Spinner) findViewById(R.id.lecturespinner);
ArrayAdapter<String> lectureadapter = new ArrayAdapter<String>
(this, android.R.layout.simple_spinner_dropdown_item, lectureManager.getLectureNames());
lectureadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(lectureadapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "HEYYY", Toast.LENGTH_LONG).show();
Intent displayLectureIntent = new Intent(getBaseContext(), LectureActivity.class);
displayLectureIntent.putExtra("lectureExtra",
lectureManager.returnLecture(adapterView.getItemAtPosition(position).toString()));
startActivity(displayLectureIntent);
}
#Override
public void onNothingSelected(AdapterView<?> adapter) {}
});
}
please add "select" string on lectureManager.getLectureNames() array at the top
so that the array's size is increased by 1
And setSelectedIndex to 0 .
and
modify onItemSelected method as followings
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "HEYYY", Toast.LENGTH_LONG).show();
Intent displayLectureIntent = new Intent(getBaseContext(), LectureActivity.class);
displayLectureIntent.putExtra("lectureExtra",
lectureManager.returnLecture(adapterView.getItemAtPosition(position).toString()));
**if(position !=0){
startActivity(displayLectureIntent);
}
else{
Toast.makeText(getApplicationContext(), " select the lecture.", Toast.LENGTH_LONG).show();**
}
}

Beginner Android: ListView to affect the next class

I am a beginner programmer so please bear with me. I am trying to create an app where the item in the list view affects what will be displayed in the next activity. So far, I have the list activity:
public class Primary extends ListActivity{
private static final String[] items = {"Item1", "Item2", "Item3", "item4", "Item5"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items));
TextView heading =(TextView)findViewById(R.id.listViewHeading);
heading.setText("Primary");
}
public void onListItemClick(ListView parent, View v, int position, long id){
}
and for the second activity, I have this:
public class ImageActivity extends Activity{
TextView heading;
ImageView image;
TextView text;
public static final String[] headings={"heading 1", "heading 2", "heading 3", "heading 4", "heading 5",};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image_activity);
heading = (TextView)findViewById(R.id.adHeading);
image = (ImageView)findViewById(R.id.adImage);
text =(TextView)findViewById(R.id.adText);
addInfo();
}
private void addInfo() {
heading.setText(headings[x]);
image.setImageResource(images[x]);
text.setText(text[x]);
}
How can i make it so that the heading, image, and text change based on what item in the list view was selected?
In the listview Activity.
Intent i = new Intent(this, ImageActivity.class);
i.putExtra("data", data);
startActivity(i);
The next Acitivty onCreate() method.
final String data = getIntent().getStringExtra("data");
I think u want to set the heading, image and text in second activity, related to first activity's selected index in list.
just do 1 thing, put following code in 1st activity
public void onListItemClick(ListView parent, View v, int position, long id)
{
Intent intent = new Intent(this.getApplicationContext(), ImageActivity.class);
intent.putExtra("pos", position);
startActivity(intent);
}
so, now u r passing the position of item selected in list.
now, put following code in next activity
private void addInfo()
{
Bundle ext = getIntent().getExtras();
if(ext != null)
{
int pos= ext.getInteger("pos");
// ext.getInt("pos");
heading.setText(headings[pos]);
// hey, frend, you don't have any array for selecting image-name and text
// image.setImageResource(images[x]);
// text.setText(text[x]);
}
}
Use the "extras" feature that are part of an Intent.
When you call start ImageActivity from Primary, you can use a 'extras' to pass information between the two.
See this link for details.
I'll give you a basic example here. When the list item is clicked, put the data that you want ImageActivity to have into the intent using "putExtra".
Intent intent = new Intent(getBaseContext(), ImageActivity.class);
String data = "somedata";
intent.putExtra("DATA", data);
startActivity(intent)
Then, in ImageActivity onCreate, retrieve the data like this:
Bundle extras = getIntent().getExtras();
if(extras !=null) {
String data= extras.getString("DATA"); // matches the tag used in putExtra
}
Once you have retrieved the data, set the necessary views.
use below code
public void onListItemClick(ListView parent, View v, int position, long id)
{
Intent intent = new Intent(Primary.this, ImageActivity.class);
intent.putExtra("selected value", item[position]);
startActivity(intent);
}
in ImageActivity class:in oncreate (or you can put item variable as global)
String item = getIntent().getStringExtra("Selected value");

Categories