I am creating simple contacts app in android. MainActivity consist of listview displaying image and name. I am using a model for setting and getting data and ArrayList to pass the data to next activity. When I click on single listview item. It should display next activity displaying contact details.
MainActivity.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
String[] name={
"Adam",
"John",
"Jasmine"
};
int[] image={
R.drawable.img1,
R.drawable.img2,
R.drawable.img3
};
String[] mobile_no={
"03349875429",
"03458294792",
"03318245801",
};
String[] email={
"adam123#yahoo.com",
"john123#gmail.com",
"jasmine456#hotmail.com"
};
String[] url={
"https://www.google.com.pk/",
"https://www.google.com.pk/",
"https://www.google.com.pk/"
};
ContactModel contact;
ArrayList<ContactModel> contact_list=new ArrayList<ContactModel>();
ListView ls;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ls=(ListView)findViewById(R.id.listView);
for(int i=0;i<name.length;i++){
contact=new ContactModel();
contact.setImage(image[i]);
contact.setName(name[i]);
contact.setMobile_no(mobile_no[i]);
contact.setEmail(email[i]);
contact.setUrl(url[i]);
contact_list.add(contact);
}
CustomBaseAdapter adapter=new CustomBaseAdapter(this,contact_list);
ls.setAdapter(adapter);
ls.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
ContactModel contacts=contact_list.get(i);
Intent intent=new Intent(getApplicationContext(),ContactDetails.class);
intent.putExtra("contacts",contacts);
startActivity(intent);
}
});
}
}
CustomeBaseAdapter.java
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomBaseAdapter extends BaseAdapter {
Activity activity;
ArrayList<ContactModel> contact;
LayoutInflater inflator;
TextView name;
ImageView image;
public CustomBaseAdapter(Activity activity, ArrayList<ContactModel> contact) {
this.activity=activity;
this.contact=contact;
inflator=activity.getLayoutInflater();
}
#Override
public int getCount() {
return contact.size();
}
#Override
public Object getItem(int i) {
return contact.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v=view;
if(view==null){
v=inflator.inflate(R.layout.contact_list_,null);
}
name=(TextView)v.findViewById(R.id.name_textView);
image=(ImageView)v.findViewById(R.id.imageView);
ContactModel c=(ContactModel) getItem(i);
name.setText(c.getName());
image.setImageResource(c.getImage());
return v;
}
}
ContactDetails.java
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class ContactDetails extends AppCompatActivity {
ImageView imageView;
TextView nameView;
TextView mobileView;
TextView emailtextview;
TextView urlView;
ImageView callButton;
ImageView messageButton;
ImageView emailButton;
ImageView websiteButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_details);
Intent intent=getIntent();
final ContactModel contacts=(ContactModel)intent.getSerializableExtra("contacts");
imageView=(ImageView)findViewById(R.id.imageView);
nameView=(TextView)findViewById(R.id.name_view);
mobileView=(TextView)findViewById(R.id.number_view);
emailtextview=(TextView)findViewById(R.id.email_textview);
urlView=(TextView)findViewById(R.id.url_textview);
//Buttons
callButton=(ImageView)findViewById(R.id.callButton);
messageButton=(ImageView)findViewById(R.id.message_view);
emailButton=(ImageView)findViewById(R.id.email_imageview);
websiteButton=(ImageView)findViewById(R.id.url_imageview);
imageView.setImageResource(contacts.getImage());
nameView.setText(contacts.getName());
mobileView.setText(contacts.getMobile_no());
emailtextview.setText(contacts.getEmail());
urlView.setText(contacts.getUrl());
}
}
ContactModel simply consist of setter and getter methods. Call Button etc functionality is not implemented yet. No error is displayed but when I run the project it displays 1 error: Error:java.lang.NullPointerException (no error message)
logcat:
09-25 05:09:54.006 1745-1775/system_process E/BluetoothAdapter: Bluetooth binder is null
09-25 05:11:00.001 1745-1773/system_process I/ProcessStatsService: Prepared write state in 0ms
09-25 05:16:38.974 98-98/? D/Genyd: Received Set Clipboard
09-25 05:16:38.974 98-98/? D/Genymotion: Received Set Clipboard
you can do this to resolve your problem:
ls.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//ContactModel contacts=new ContactModel();//here you did mistake
Intent intent=new Intent(getApplicationContext(),ContactDetails.class);
intent.putExtra("contacts",(Serializable) adapterView.getSelectedItem());
startActivity(intent);
}
});
In ls.setOnItemClickListener, you're passing ContactModel contacts=new ContactModel(); which is technically a blank object of ContactModel.
Now, when you're trying to set data in ContactDetails.java from that blank object that you got from Intent like this,
imageView.setImageResource(contacts.getImage());
nameView.setText(contacts.getName());
the contact object has no image or name (or other attributes for that matter) that has been previously set on it. Hence, you're getting a null pointer exception.
So, change it like below and your problem should get away.
ls.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
ContactModel contacts= contact_list.get(i);
Intent intent=new Intent(getApplicationContext(),ContactDetails.class);
Bundle bundle = new Bundle();
bundle.putSerializable("contacts",contacts);
intent.putExtras(bundle);
startActivity(intent);
}
});
And in ContactDetails.java, get the object like this.
Intent intent=getIntent();
Bundle bundle = intent.getExtras();
final ContactModel contacts=(ContactModel)bundle.getSerializable("contacts");
Related
I made an ImageAdapter class that contains images and an activity that contains 2 buttons, on click each one opens a new activity with a viewpager. The 2 viewpagers have different images and this is where my inexperience comes in.
I took the easy way and duplicated the ImageAdapter (named it ImageAdapter2) and linked it to the 2nd viewpager. visual representation
It works fine, but what I'm trying to do is clean it up and do it all through 1 adapter and 1 viewpager. I tried to do it through Intent getStringExtra but it didn't recognize Intent method. Here are my classes:
ImageAdapter (ImageAdapter2 is the same, just has different images in sliderImageId):
package hr.cnzd.prepoznajmoenasilje;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
public class ImageAdapter extends PagerAdapter {
Context mContext;
ImageAdapter(Context context){
this.mContext = context;
}
#Override
public boolean isViewFromObject(View view, Object o){
return view == ((ImageView) o);
}
private int[] sliderImageId = new int[]{
R.drawable.djeca01, R.drawable.djeca02, R.drawable.djeca03, R.drawable.djeca04, R.drawable.djeca05, R.drawable.djeca06, R.drawable.djeca07, R.drawable.djeca08
};
#Override
public Object instantiateItem(ViewGroup viewGroup, int position){
ImageView imageView = new ImageView(mContext);
imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageResource(sliderImageId[position]);
((ViewPager) viewGroup).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup viewGroup, int position, Object o){
((ViewPager) viewGroup).removeView((ImageView) o);
}
#Override
public int getCount(){
return sliderImageId.length;
}
}
Activity with buttons:
package hr.cnzd.prepoznajmoenasilje;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import androidx.appcompat.app.AppCompatActivity;
public class MA_Savjeti extends AppCompatActivity {
private ImageButton imageButtonDjeca;
private ImageButton imageButtonOdrasli;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ma__savjeti);
imageButtonDjeca = findViewById(R.id.imgBtnDjeca);
imageButtonDjeca.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openActivitySavjetiDjeca();
}
});
imageButtonOdrasli = findViewById(R.id.imgBtnOdrasli);
imageButtonOdrasli.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openActivitySavjetiOdrasli();
}
});
}
public void openActivitySavjetiDjeca() {
Intent intent = new Intent(this, Savjeti_Djeca.class);
intent.putExtra("savjeti", "djeca");
startActivity(intent);
}
public void openActivitySavjetiOdrasli() {
Intent intent = new Intent(this, Savjeti_Odrasli.class);
intent.putExtra("savjeti", "odrasli");
startActivity(intent);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
}
Activity with viewpager (other activity with viewpager has the same code, just calls ImageAdapter2)
package hr.cnzd.prepoznajmoenasilje;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
public class Savjeti_Djeca extends AppCompatActivity {
ViewPager viewPager;
ImageAdapter imageAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.savjeti_djeca);
viewPager = findViewById(R.id.viewpager);
imageAdapter = new ImageAdapter(this);
viewPager.setAdapter(imageAdapter);
}
}
TLDR: I have 2 ImageAdapters and 2 Viewpagers, but I wanna do it through 1 ImageAdapter and 1 Viewpager (2 buttons on a previous activity decide which set of images is shown on the viewpager)
Solved it using ViewPager2 instead of this way.
So I have two Adapter class for RecyclerView. I want the ImageView inside one Adapter class to display the other Adapter class
I already tried to use intent on MainActivity
// listener for image
cardViewHolder.photo.setOnClickListener(new CustomOnItemClick(
i, new CustomOnItemClick.OnItemClickCallback() {
#Override
public void onItemClicked(View view, int position) {
Intent detail = new Intent(context,DetailAdapter.class);
context.startActivity(detail);
}
}
));
here is the link for what the application supposed to be
https://ibb.co/gmnnghw
https://giphy.com/gifs/Y3NK0lHfAcN1dGbCZX
CardViewDeviceAdapter
package com.example.myapplication;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import java.util.ArrayList;
public class CardViewDeviceAdapter extends RecyclerView.Adapter<CardViewDeviceAdapter.CardViewHolder> {
private Context context;
private ArrayList<Device> deviceArrayList;
private ArrayList<Device> getDeviceArrayList() {
return deviceArrayList;
}
public void setDeviceArrayList(ArrayList<Device> deviceArrayList) {
this.deviceArrayList = deviceArrayList;
}
public CardViewDeviceAdapter(Context context) {
this.context = context;
}
#Override
public CardViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_device, viewGroup, false);
return new CardViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull CardViewHolder cardViewHolder, int i) {
Device d = getDeviceArrayList().get(i);
Glide.with(context)
.load(d.getPhoto())
.apply(new RequestOptions().override(350, 550))
.into(cardViewHolder.photo);
cardViewHolder.title.setText(d.getTitle());
cardViewHolder.detail.setText(d.getDetail());
// listener untuk button favorite
cardViewHolder.favorite.setOnClickListener(new CustomOnItemClick(
i, new CustomOnItemClick.OnItemClickCallback() {
#Override
public void onItemClicked(View view, int position) {
Toast.makeText(context, "Favorite device"+getDeviceArrayList()
.get(position)
.getTitle()
, Toast.LENGTH_SHORT).show();
}
}
));
// listener untuk button share
cardViewHolder.share.setOnClickListener(new CustomOnItemClick(
i, new CustomOnItemClick.OnItemClickCallback() {
#Override
public void onItemClicked(View view, int position) {
Toast.makeText(context, "Share device"+getDeviceArrayList()
.get(position)
.getTitle()
, Toast.LENGTH_SHORT).show();
}
}
));
// listener untuk image
cardViewHolder.photo.setOnClickListener(new CustomOnItemClick(
i, new CustomOnItemClick.OnItemClickCallback() {
#Override
public void onItemClicked(View view, int position) {
Intent detail = new Intent(context, DetailAdapter.class);
context.startActivity(detail);
}
}
));
}
#Override
public int getItemCount() {
return getDeviceArrayList().size();
}
public class CardViewHolder extends RecyclerView.ViewHolder {
ImageView photo;
TextView title, detail;
Button favorite, share;
public CardViewHolder(View itemView) {
super(itemView);
photo = itemView.findViewById(R.id.pc_photo);
title = itemView.findViewById(R.id.pc_name);
detail = itemView.findViewById(R.id.pc_details);
favorite = itemView.findViewById(R.id.pc_favourite);
share = itemView.findViewById(R.id.pc_share);
}
}
}
DetailAdapter
package com.example.myapplication;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import java.util.ArrayList;
public class DetailAdapter extends RecyclerView.Adapter<DetailAdapter.DetailHolder> {
private Context context;
private ArrayList<Device> deviceArrayList;
private ArrayList<Device> getDeviceArrayList() {
return deviceArrayList;
}
#NonNull
#Override
public DetailAdapter.DetailHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.detail_adapter, viewGroup, false);
return new DetailAdapter.DetailHolder(view);
}
#Override
public void onBindViewHolder(#NonNull DetailAdapter.DetailHolder detailHolder, int i) {
Device d = getDeviceArrayList().get(i);
Glide.with(context)
.load(d.getPhoto())
.apply(new RequestOptions().override(350, 550))
.into(detailHolder.photo);
detailHolder.title.setText(d.getTitle());
detailHolder.detail.setText(d.getDetail());
detailHolder.summary.setText(d.getSummary());
detailHolder.origin.setText(d.getOrigin());
detailHolder.market_value.setText(d.getMarket_value());
detailHolder.consumer.setText(d.getConsumer());
}
#Override
public int getItemCount() {
return getDeviceArrayList().size();
}
public class DetailHolder extends RecyclerView.ViewHolder {
ImageView photo;
TextView title, detail, summary, origin, market_value, consumer;
public DetailHolder(View view) {
super(view);
photo = view.findViewById(R.id.photo_detail);
title = view.findViewById(R.id.title_title);
detail = view.findViewById(R.id.detail_title);
summary = view.findViewById(R.id.detail_detail);
origin = view.findViewById(R.id.origin_year);
market_value = view.findViewById(R.id.market_value);
consumer = view.findViewById(R.id.konsumer);
}
}
}
Right now it asks for explicit activity on AndroidManifest.xml ,
but I can't assign DetailAdapter to AndroidManifest.xml
Logcat
2019-05-29 17:38:59.097 8897-8897/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 8897
android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.myapplication/com.example.myapplication.DetailAdapter}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2012)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1675)
at android.app.Activity.startActivityForResult(Activity.java:4586)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:767)
at android.app.Activity.startActivityForResult(Activity.java:4544)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:754)
at android.app.Activity.startActivity(Activity.java:4905)
at android.app.Activity.startActivity(Activity.java:4873)
at com.example.myapplication.CardViewDeviceAdapter$3.onItemClicked(CardViewDeviceAdapter.java:89)
at com.example.myapplication.CustomOnItemClick.onClick(CustomOnItemClick.java:16)
at android.view.View.performClick(View.java:6608)
at android.view.View.performClickInternal(View.java:6585)
at android.view.View.access$3100(View.java:782)
at android.view.View$PerformClick.run(View.java:25945)
at android.os.Handler.handleCallback(Handler.java:874)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:198)
at android.app.ActivityThread.main(ActivityThread.java:6729)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
App crashses when tapping on Image
You've got all the concept of RecyclerView wrong. Check out how to use RecyclerView from
Simple RecyclerView Example.
What you're trying to do is launch RecyclerView like an Activity. Your RecyclerView is not an activity, it is a view.
In the gif you've attached to shown what you want to accomplish, it's a completely different thing. After clicking the item in RecyclerView, a new activity is launched with SharedElement transition. Your DetailAdapter should be AppCompatActivity.
To correct your error, make your DetailAdapter extend AppCompatActivity, after doing that, while launching the DetailAdapter with Intent, pass the data like title, detail through Intent.
I have made this app where in one particular activity i have a all the items listed in a list view. when you click the list item it goes to another activity where similar thing is happening. after that i was the clicked list items to be converted into a strings and transported into a 3rd activity where i can display those.
when i try to display them this shows in the text view where the clicked text item should have appeared:
this is code for the first activity:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.internal.Objects;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class TicketCategory extends AppCompatActivity {
public static String Category;
public String getCategory() {
return Category;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ticket_category);
populateTicketCategoryList();
final ListView listView = (ListView) findViewById(R.id.lvTicketCategory);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (i == 0) {
Category = listView.getItemAtPosition(i).toString();
Intent intent = new Intent(TicketCategory.this, Subcategory.class);
startActivity(intent);
}
}
});
}
private void populateTicketCategoryList()
{
ArrayList<CompTicketCategory> arrayOfTicket = CompTicketCategory.getTicket();
CompTicketCategoryAdapter adapter = new CompTicketCategoryAdapter(this, arrayOfTicket);
ListView listView = (ListView) findViewById(R.id.lvTicketCategory);
listView.setAdapter(adapter);
}
}
the code for the second activity is:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class Subcategory extends AppCompatActivity {
public String Category;
public static String Subcat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subcategory);
populateSubcategoryList();
final ListView listView = (ListView) findViewById(R.id.lvSubcategory);
ArrayAdapter arrayAdapter = new ArrayAdapter<String>(Subcategory.this, android.R.layout.simple_list_item_1,arrayList);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Subcat = listView.getItemAtPosition(i).toString();
Intent intent = new Intent(Subcategory.this, SubmitTicket.class);
startActivity(intent);
}
});
and this is the code for the activity where both of the clicked items should be displayed:
public class SubmitTicket extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_submit_ticket);
Spinner spinner = (Spinner) findViewById(R.id.spinner_priority);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.priority_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
final Button butt = findViewById(R.id.submit);
butt.setOnClickListener(new View.OnClickListener()
{
public void onClick (View view){
Toast.makeText(getApplicationContext(), "The ticket has been submitted", Toast.LENGTH_SHORT).show();
}
});
TextView textView = (TextView)findViewById(R.id.Category_submit_report);
textView.setText(TicketCategory.Category);
TextView tv = (TextView)findViewById(R.id.Subcategory_submit_report);
tv.setText(Subcategory.Subcat);
}
Please help me. i would appreciate any output. thanks!
UPDATE:
after trying
CompTicketCategory model = listView.getItemAtPosition(i);
Category=model.Category; // your Category variable
Category=model.getCategory();
this error is shown;
screenshot
You can use Intent Extra Feature.
In the First Activity,
Intent intent = new Intent(Subcategory.this, SubmitTicket.class);
switch1.putExtra("deviceID", listView.getItemAtPosition(i).toString(););
startActivity(intent);
Then Next activity recall them,
Intent intent = getIntent();
String data = intent.getStringExtra("data");
Try this in your TicketCategory actvity
Use this:
CompSubcategory model = listView.getItemAtPosition(i);
Category=model.Category; // your Category variable
Category=model.getCategory(); // or use getter setter method
Instead of this:
Category = listView.getItemAtPosition(i).toString();
happy new year to all of you.
I am having a problem with the method onItemClickListener, because when I tried to toast the position and id ,in my second activity, I get zeros.
here is the code, I rely on the position of the image in the array that is why I need to get the position/id accurately.
+
I am duplicating my array in both activities because I don't know how to access it from the second activity?
MainActivity.java
package swe.trial;
import android.content.Context;
import android.widget.ImageView;
import android.view.View;
import android.view.ViewGroup;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.AdapterView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView items = (GridView) findViewById(R.id.itemsList);
items.setAdapter(new item_adapter(this));
items.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//if an item is clicked or selceted,then go to the activity itemDetails:
Intent i= new Intent (MainActivity.this, itemDetails.class);
i.putExtra("position", position);
i.putExtra("id", id);
startActivity(i);
}
});
}
}
class item_adapter extends BaseAdapter {
Integer[] picsId = {
R.drawable.pic1,
R.drawable.pic2,
R.drawable.pic3,
R.drawable.pic4,
R.drawable.pic5,
R.drawable.pic6,
R.drawable.pic7};
private Context context;
public item_adapter(Context context) {
this.context = context;
}
public Object getItem(int position) {
return null;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imgview= new ImageView(context);
imgview.setLayoutParams(new GridView.LayoutParams(250,250));
imgview.setScaleType(ImageView.ScaleType.CENTER_CROP);
imgview.setPadding(20,20,20,20);
imgview.setImageResource(picsId[position]);
return imgview;
}
public long getItemId(int position) {
return position;
}
public int getCount (){
return picsId.length;
}
}
itemDetails.java
package swe.trial;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.widget.ImageView;
import android.widget.TextView;
import android.app.Activity;
import android.net.Uri;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by good on 1/01/17.
*/
public class itemDetails extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.item);
ArrayList<item> items = new ArrayList<item>();
// items item1=
// Bundle d = getIntent().getExtras();
int id=0;getIntent().getIntExtra("id",id);
int position=0;
getIntent().getIntExtra("position", position);
Toast.makeText( this, "id= " +id + " . and posistion= "+ position, Toast.LENGTH_LONG).show();
Integer[] picsId = {
R.drawable.pic1,
R.drawable.pic2,
R.drawable.pic3,
R.drawable.pic4,
R.drawable.pic5,
R.drawable.pic6,
R.drawable.pic7
};
ImageView imgview = (ImageView) findViewById(R.id.item_image);
imgview.setImageResource(picsId[id+ 1]);
TextView txt= (TextView) findViewById(R.id.pricetxtview);
txt.setText("This is the description provided." + id);
//(id);
// item item1 = {"Red rose", "#/drawable/", 1, 1.25};
// items.add(item1);
// now i will search for the array that holds the given id. and i will retrieve its info and display it again
// in the new layout.
}
}
You misunderstand the way you should use intents.
The right form is like this :
int id =getIntent().getIntExtra("id",0);
int position = getIntent().getIntExtra("position", 0);
when you use getIntExtra , the second parameter is the default value. In case there is not such value with that tag in your intent, it will return that default value.
See Google docs for more info
You have to fetch value according the following way,
int id=0;
int position=0;
i=getIntent().getIntExtra("id",id);
position= getIntent().getIntExtra("position", position);
Toast.makeText( this, "id= " +id + " . and posistion= "+ position, Toast.LENGTH_LONG).show();
Multiple markers at this line
- position cannot be resolved to a variable
- Cannot refer to a non-final variable items inside an inner class defined in a different method
int multiple=0;
ImageView imageView;
TextView tot_calories;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.items_details);
Spinner mspin=(Spinner) findViewById(R.id.spinner1);
Integer[] items = new Integer[]{1,2,3,4};
ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this,android.R.layout.simple_spinner_item, items);
mspin.setAdapter(adapter);
TextView name_select=(TextView)findViewById(R.id.SelectedName);
name_select.setText(constant.food_items[constant.SelectedIndex]);
imageView =(ImageView) findViewById(R.id.imagedetail);
UpdateImage(constant.food_items[constant.SelectedIndex]);
TextView calories=(TextView)findViewById(R.id.calories111);
calories.setText(constant.food_calories[constant.index]+"");
tot_calories=(TextView)findViewById(R.id.caloriestotal);
mspin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
// Your code here
multiple=items[position]*constant.food_calories[constant.index];
}
public void onNothingSelected(AdapterView<?> adapterView) {
return;
}
});
tot_calories.setText(""+multiple);
}
Update this line of code with this:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
public class itemsdetail extends Activity {
int multiple=0;
ImageView imageView;
TextView tot_calories;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.items_details);
Spinner mspin=(Spinner) findViewById(R.id.spinner1);
Integer[] items = new Integer[]{1,2,3,4};
ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this,android.R.layout.simple_spinner_item, items);
mspin.setAdapter(adapter);
TextView name_select=(TextView)findViewById(R.id.SelectedName);
name_select.setText(constant.food_items[constant.SelectedIndex]);
imageView =(ImageView) findViewById(R.id.imagedetail);
UpdateImage(constant.food_items[constant.SelectedIndex]);
TextView calories=(TextView)findViewById(R.id.calories111);
calories.setText(constant.food_calories[constant.index]+"");
tot_calories=(TextView)findViewById(R.id.caloriestotal);
mspin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
// Your code here
multiple=items[position]*constant.food_calories[constant.index];
}
public void onNothingSelected(AdapterView<?> adapterView) {
return;
}
});
tot_calories.setText(""+multiple);
}
}
Goodluck!