I'm trying to pass data from a custom listview to a new activity and populate its TextViews. It does work but it always takes the first position that was added and passes it through. How do I get it to pass the data clicked on?
MainActivity
package uk.co.jaunt_app.jaunt;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.crashlytics.android.answers.Answers;
import com.crashlytics.android.answers.CustomEvent;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import java.util.ArrayList;
import java.util.List;
import static uk.co.jaunt_app.jaunt.R.id.Posts;
public class MainActivity extends AppCompatActivity {
private FloatingActionButton addmap;
private Button settingbtn;
private TextView mNameTextView;
private TextView mEmailTextView;
ListView mPosts;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
ArrayAdapter<String> adapter;
private FirebaseAuth auth;
private ArrayList<feed> feedPop = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.drawable.jauntlogodark);
getSupportActionBar().setDisplayUseLogoEnabled(true);
setContentView(R.layout.activity_main);
Firebase.setAndroidContext(this);
Firebase ref = new Firebase(Config.FIREBASE_URL);
FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
String uid = currentFirebaseUser.getUid();
Firebase usersRef = ref.child("Users").child(uid).child("name");
Firebase emailRef = ref.child("Users").child(uid).child("email");
Firebase postRef = ref.child("Users").child(uid).child("Maps");
postRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (final DataSnapshot postSnapshot : snapshot.getChildren()) {
//Getting the data from snapshot
Person person = postSnapshot.getValue(Person.class);
final String mapName = person.getMapName();
final String mapid = person.getMapID();
final String mapStartLat = person.getStartLat();
final String mapStartLong = person.getStartLong();
final String mapEndLat = person.getEndLat();
final String mapEndLong = person.getEndLong();
adapter.notifyDataSetChanged();
feedPop.add(
new feed(mapName, mapStartLat, mapStartLong, mapEndLat, mapEndLong));
final ArrayAdapter<feed> adapter = new feedArrayAdapter(MainActivity.this, 0, feedPop);
ListView listView = (ListView) findViewById(R.id.customListView);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(MainActivity.this, ViewUserMapActivity.class);
intent.putExtra("mapName", mapName.toString());
intent.putExtra("mapStartLat", mapStartLat.toString());
intent.putExtra("mapStartLong", mapStartLong.toString());
intent.putExtra("mapEndLat", mapEndLat.toString());
intent.putExtra("mapEndLong", mapEndLong.toString());
startActivity(intent);
}
});
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Toast.makeText(getApplicationContext(),
"Cancelled", Toast.LENGTH_LONG)
.show();
}
});
//create property elements
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
mPosts = (ListView) findViewById(Posts);
mPosts.setAdapter(adapter);
List<Nav> navList= new ArrayList<Nav>();
navList.add(new Nav("Profile"));
navList.add(new Nav("Feed"));
navList.add(new Nav("Maps"));
navList.add(new Nav("Most Popular"));
navList.add(new Nav("Settings"));
navList.add(new Nav("Report a Bug"));
ArrayAdapter<Nav> navadapter = new ArrayAdapter<Nav>(this,android.R.layout.simple_list_item_1, navList);
final ListView lv= (ListView) findViewById(R.id.left_drawer);
lv.setAdapter(navadapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int itemPosition = position;
switch(itemPosition) {
case 0:
Intent menuItem = new Intent(MainActivity.this, UserMapActivity.class);
startActivity(menuItem);
break;
case 1:
menuItem = new Intent(MainActivity.this, UserMapActivity.class);
startActivity(menuItem);
break;
case 2:
menuItem = new Intent(MainActivity.this, UserMapActivity.class);
startActivity(menuItem);
break;
case 3:
menuItem = new Intent(MainActivity.this, UserMapActivity.class);
startActivity(menuItem);
break;
case 4:
menuItem = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(menuItem);
break;
case 5:
menuItem = new Intent(MainActivity.this, UserMapActivity.class);
startActivity(menuItem);
break;
}
}
});
mNameTextView = (TextView) findViewById(R.id.NameTextView);
usersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = dataSnapshot.getValue(String.class);
mNameTextView.setText(name);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
mEmailTextView = (TextView) findViewById(R.id.EmailTextView);
emailRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String email = dataSnapshot.getValue(String.class);
mEmailTextView.setText(email);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
addmap = (FloatingActionButton) findViewById(R.id.add_map);
addmap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Answers.getInstance().logCustom(new CustomEvent("Added Map"));
Intent intent = new Intent(MainActivity.this, MapStartActivity.class);
startActivity(intent);
}
});
settingbtn = (Button) findViewById(R.id.settingbtn);
settingbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_menu_drawer, menu);
return true;
}
}
//custom ArrayAdapter
class feedArrayAdapter extends ArrayAdapter<feed>{
private Context context;
private List<feed> feedPop;
//constructor, call on creation
public feedArrayAdapter(Context context, int resource, ArrayList<feed> objects) {
super(context, resource, objects);
this.context = context;
this.feedPop = objects;
}
//called when rendering the list
public View getView(int position, View convertView, ViewGroup parent) {
//get the property we are displaying
feed feed = feedPop.get(position);
//get the inflater and inflate the XML layout for each item
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.feed_listview, null);
TextView others = (TextView) view.findViewById(R.id.others);
TextView mapname = (TextView) view.findViewById(R.id.address);
//set address and description
String completeOthers = feed.getFeedStartLat() + ", " + feed.getFeedStartLong() + ", " + feed.getFeedEndLat() + ", " + feed.getFeedEndLong();
others.setText(completeOthers);
//set address and description
String completeAddress = feed.getFeedName();
mapname.setText(completeAddress);
return view;
}
}
Get value from ArrayList based on position then pass to activity
intent.putExtra("mapName", feedPop.get(position).getmapName().toString());
Related
I have a small app that uses a ListView, each item having a play button, an open/close button, and an ImageView whose visibilty is set to View.GONE. When I press the open/close button, it should set the ImageView in that one list item to View.VISIBLE, change the open/close button, and close any other list items that are displaying the ImageView as VISIBLE and change their open/close button to reflect closed. This is my onClick in my custom ArrayAdapter.
boolean open = false;
imgOpen_Close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!open){
openClose.setImageResource(R.drawable.open_arrow);
mainImage.setVisibility(View.VISIBLE);
open = true;
}else{
openClose.setImageResource(R.drawable.close_arrow);
mainImage.setVisibility(View.VISIBLE);
open = false;
}
});
How do I access a View in one list item from another list item?
Entire Custom ArrayAdapter.
package net.androidbootcamp.mypersonalplaylist;
import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class MyListAdapter extends ArrayAdapter<String> {
private final Activity context;
private final String[] songs;
private final Integer[] imgID;
MediaPlayer mpKickStart, mpGirlsGirls, mpHomeSweetHome;
public MyListAdapter(Activity context, String[] songs, Integer[] imgID){
super(context, R.layout.list_view_custom, songs);
this.context=context;
this.songs=songs;
this.imgID=imgID;
}
public View getView(final int position, View view, ViewGroup parent){
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.list_view_custom, null, true);
TextView txtSongName = rowView.findViewById(R.id.txtSongName);
final ImageView imgCoverArt = rowView.findViewById(R.id.imgCoverArt);
final ImageView imgPlayButton = rowView.findViewById(R.id.imgPlayButton);
final ImageView imgOpen_Close = rowView.findViewById(R.id.imgOpen_Close);
txtSongName.setText(songs[position]);
imgCoverArt.setImageResource(imgID[position]);
mpKickStart = new MediaPlayer();
mpKickStart = MediaPlayer.create(context, R.raw.kickstartmyheart);
mpGirlsGirls = new MediaPlayer();
mpGirlsGirls = MediaPlayer.create(context, R.raw.girlsgirlsgirls);
mpHomeSweetHome = new MediaPlayer();
mpHomeSweetHome = MediaPlayer.create(context, R.raw.homesweethome);
imgPlayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (position){
case 0:
break;
case 1:
break;
case 2:
break;
default:
break;
}
}
});
imgOpen_Close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("POSITION", "Position Clicked: " + position);
}
});
return rowView;
}
}
MainActivity
package net.androidbootcamp.mypersonalplaylist;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
ListView list;
String[] songs = {"Name 1", "Name 2", "Name 3"};
Integer[] imgID = {R.drawable.kickstart_my_heart, R.drawable.girls_girls_girls, R.drawable.home_sweet_home};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyListAdapter adapter = new MyListAdapter(this, songs, imgID);
list = findViewById(R.id.listView);
list.setAdapter(adapter);
}
}
PostImage not displaying from firebase database into recyclerview.PostImage displaying in firebase database but not in recyclerview. 3 text fields and 1 CircleImageView is displaying in recyclerview.
No error in sync and build.no error in install, no crashing of app.
Main Activity
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;
import android.content.Context;
import android.content.Intent;
import android.media.Image;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
import java.util.Objects;
import de.hdodenhof.circleimageview.CircleImageView;
import swiftstartechnology.co.prasa.Posts;
import swiftstartechnology.co.prasa.R;
public class MediaActivity extends AppCompatActivity {
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
private RecyclerView postList;
private Toolbar mToolbar;
private CircleImageView NavProfileImage;
private TextView NavProfileUserName;
private ImageButton AddNewPostButton;
private FirebaseAuth mAuth;
private DatabaseReference UsersRef;
private DatabaseReference PostsRef;
String currentUserID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_media);
mAuth = FirebaseAuth.getInstance ();
currentUserID = mAuth.getCurrentUser ().getUid ();
UsersRef = FirebaseDatabase.getInstance ().getReference ().child ("Users");
PostsRef = FirebaseDatabase.getInstance ().getReference ().child ("Posts");
AddNewPostButton = (ImageButton) findViewById (R.id.add_new_post_button);
mToolbar = (Toolbar) findViewById (R.id.media_page_toolbar);
setSupportActionBar (mToolbar);
getSupportActionBar ().setTitle ("Home");
AddNewPostButton = (ImageButton) findViewById (R.id.add_new_post_button);
drawerLayout = (DrawerLayout) findViewById (R.id.drawable_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle (MediaActivity.this, drawerLayout, R.string.drawer_open, R.string.drawer_close);
drawerLayout.addDrawerListener (actionBarDrawerToggle);
actionBarDrawerToggle.syncState ();
getSupportActionBar ().setDisplayHomeAsUpEnabled (true);
navigationView = (NavigationView) findViewById (R.id.navigation_view);
postList = (RecyclerView) findViewById (R.id.all_users_post_list);
postList.setHasFixedSize (true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager (this);
linearLayoutManager.setReverseLayout (true);
linearLayoutManager.setStackFromEnd (true);
postList.setLayoutManager (linearLayoutManager);
View navView = navigationView.inflateHeaderView (R.layout.navigation_header);
NavProfileImage = (CircleImageView) navView.findViewById (R.id.nav_profile_image);
NavProfileUserName = (TextView) navView.findViewById (R.id.nav_user_full_name);
UsersRef.child (currentUserID).addValueEventListener (new ValueEventListener () {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists ()) {
if (dataSnapshot.hasChild ("fullname")) {
String fullname = dataSnapshot.child ("fullname").getValue ().toString ();
NavProfileUserName.setText (fullname);
}
if (dataSnapshot.hasChild ("profileimage")) {
String image = dataSnapshot.child ("profileimage").getValue ().toString ();
Picasso.get ().load (image).placeholder (R.drawable.profilenew).into (NavProfileImage);
} else {
Toast.makeText (MediaActivity.this, "Profile name do not exists...", Toast.LENGTH_SHORT).show ();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item)
{
UserMenuSelector(item);
return false;
}
});
AddNewPostButton.setOnClickListener (new View.OnClickListener () {
#Override
public void onClick(View v) {
SendUserToPostActivity ();
}
});
DisplayAllUsersPosts();
}
private void DisplayAllUsersPosts() {
FirebaseRecyclerOptions<Posts> options=new FirebaseRecyclerOptions.Builder<Posts>().setQuery(PostsRef,Posts.class).build();
FirebaseRecyclerAdapter<Posts, PostsViewHolder> firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<Posts, PostsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull PostsViewHolder holder, int position, #NonNull Posts model) {
holder.username.setText(model.getFullname());
holder.time.setText(" " +model.getTime());
holder.date.setText(" "+model.getDate());
holder.description.setText(model.getDescription());
Picasso.get().load(model.getProfileimage()).into(holder.user_profile_image);
Picasso.get().load(model.getPostimage()).into(holder.postImage);
}
#NonNull
#Override
public PostsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view=LayoutInflater.from(parent.getContext()).inflate(R.layout.all_posts_layout,parent,false);
PostsViewHolder viewHolder=new PostsViewHolder(view);
return viewHolder;
}
};
postList.setAdapter(firebaseRecyclerAdapter);
firebaseRecyclerAdapter.startListening();
}
public static class PostsViewHolder extends RecyclerView.ViewHolder{
ImageView postImage;
TextView username,date,time,description;
CircleImageView user_profile_image;
public PostsViewHolder(View itemView) {
super(itemView);
username=itemView.findViewById(R.id.post_user_name);
date=itemView.findViewById(R.id.post_date);
time=itemView.findViewById(R.id.post_time);
description=itemView.findViewById(R.id.post_description);
postImage=itemView.findViewById(R.id.post_image);
user_profile_image=itemView.findViewById(R.id.post_User_image);
}
}
private void SendUserToPostActivity()
{
Intent addNewPostIntent = new Intent(MediaActivity.this, PostActivity.class);
startActivity(addNewPostIntent);
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
if(currentUser == null)
{
SendUserToLoginActivity();
}
else
{
CheckUserExistence();
}
}
private void CheckUserExistence() {
final String current_user_id = mAuth.getCurrentUser().getUid();
UsersRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(!dataSnapshot.hasChild(current_user_id))
{
SendUserToSetupActivity();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void SendUserToSetupActivity() {
Intent setupIntent = new Intent(MediaActivity.this, SetupActivity.class);
setupIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(setupIntent);
finish();
}
private void SendUserToLoginActivity()
{
Intent loginIntent = new Intent(MediaActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
finish();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void UserMenuSelector(MenuItem item)
{
switch (item.getItemId())
{
case R.id.nav_post:
SendUserToPostActivity();
break;
case R.id.nav_profile:
Toast.makeText(this, "Profile", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_home:
Toast.makeText(this, "Home", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_friends:
Toast.makeText(this, "Friend List", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_find_friends:
Toast.makeText(this, "Find Friends", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_messages:
Toast.makeText(this, "Messages", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_settings:
Toast.makeText(this, "Settings", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_Logout:
mAuth.signOut();
SendUserToLoginActivity();
break;
}
}
}
no error message.I just need the postimage to display in recyclerview as the profile image and other text is displaying.
Hello friend please help me i am using Recylerview and implemented searchfilter but problem is that after searching the item in recylerview when i click on item it always return 0 position of the item i want actual position of list item please me help here is my code how get actual position recylerview after searching item in recylerview
here is my code
package bible.swordof.God;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, SearchView.OnQueryTextListener {
private ListView listView;
private ArrayList<String> books;
private ArrayList<String> bookid;
private ListViewAdapter adapter;
private DatabaseHelper mDBHelper = null;
private SQLiteDatabase mDb = null;
BookRecyclerAdopter bookRecyclerAdopter;
//life is awesome
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
setData();
RecyclerView bookanme = findViewById(R.id.list);
bookanme.setLayoutManager(new LinearLayoutManager(this));
bookRecyclerAdopter = new BookRecyclerAdopter(this, books);
bookanme.setAdapter(bookRecyclerAdopter);
/* adapter = new ListViewAdapter(MainActivity.this, R.layout.item_listview, books, bookid);
listView.setAdapter(adapter);*/
/* listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int booknumber=position;
String bookname=bookid.get(position);
Toast.makeText(MainActivity.this, ""+bookname, Toast.LENGTH_SHORT).show();
*//* Intent intent=new Intent(MainActivity.this,Chapters.class);
intent.putExtra("booknumber",booknumber);
intent.putExtra("bookname",bookname);
startActivity(intent);*//*
}
});
}
*/
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.search_voice_btn:
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, 10);
} else {
Toast.makeText(this, "Your Device Don't Support Speech Input", Toast.LENGTH_SHORT).show();
}
break;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 10:
if (resultCode == RESULT_OK && data != null) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
Toast.makeText(this, "" + result.get(0), Toast.LENGTH_SHORT).show();
}
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
MenuItem myActionMenuItem = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(myActionMenuItem);
searchView.setOnQueryTextListener(this);
return true;
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
Fragment fragment;
int id = item.getItemId();
if (id == R.id.home) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
} else if (id == R.id.favoruite) {
Intent intent = new Intent(this, Favourite.class);
startActivity(intent);
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void setData() {
books = new ArrayList<>();
bookid = new ArrayList<>();
mDBHelper = new DatabaseHelper(this);
mDb = mDBHelper.getReadableDatabase();
Cursor cursor = mDb.rawQuery("select b,n from key_english", new String[]{});
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
books.add(cursor.getString(1));
bookid.add(cursor.getString(0));
} while (cursor.moveToNext());
}
}
}
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String newtext) {
String userinput = newtext.toLowerCase();
List<String> newlist = new ArrayList<>();
for (String name : books) {
if (name.toLowerCase().contains(userinput)) {
newlist.add(name);
}
}
bookRecyclerAdopter.updatelist(newlist);
return true;
}
}
package bible.swordof.God;
import android.app.Activity;
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.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;
import java.util.ArrayList;
import java.util.List;
public class BookRecyclerAdopter extends RecyclerView.Adapter<BookRecyclerAdopter.Booksholder>{
private List<String> bookname;
Context context;
public BookRecyclerAdopter(Context context,List<String> bookname) {
this.bookname = bookname;
this.context=context;
}
public class Booksholder extends RecyclerView.ViewHolder {
private ImageView imageView;
private TextView bookname;
public Booksholder(#NonNull View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.image_view);
bookname = (TextView) itemView.findViewById(R.id.text);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
#Override
public Booksholder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
View view = inflater.inflate(R.layout.item_listview, viewGroup, false);
return new Booksholder(view);
}
#Override
public void onBindViewHolder(#NonNull Booksholder booksholder, final int i) {
booksholder.bookname.setText(bookname.get(i));
//get first letter of each String item
String firstLetter = String.valueOf(bookname.get(i).charAt(0));
ColorGenerator generator = ColorGenerator.MATERIAL; // or use DEFAULT
// generate random color
int color = generator.getColor(bookname.get(i));
TextDrawable drawable = TextDrawable.builder()
.buildRound(firstLetter, color); // radius in px
booksholder.imageView.setImageDrawable(drawable);
}
#Override
public int getItemCount() {
return bookname.size();
}
public void updatelist(List<String>newlist){
bookname=new ArrayList<>();
bookname.addAll(newlist);
notifyDataSetChanged();
}
}
You will need to maintain a separate list of bookname. Let's call it filteredBookname. Initially set it as bookname.
public class BookRecyclerAdopter extends RecyclerView.Adapter<BookRecyclerAdopter.Booksholder>{
private List<String> bookname;
private List<String> filteredBookname;
Context context;
public BookRecyclerAdopter(Context context,List<String> bookname) {
this.bookname = bookname;
this.filteredBookname = bookname
this.context=context;
}
...
// other pieces of code.
and instead of using bookname to populate RecyclerView items, use filteredBookname
and your update list method will be,
public void updatelist(List<String>newlist){
filteredBookname=new ArrayList<>();
filteredBookname.addAll(newlist);
notifyDataSetChanged();
}
Using the above approach, you can always find the proper position of your item in the original list bookname
The reason is that you are picking the wrong list, pick your data from filtered adapter list/model.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Books booksdata= (Books)adapterName.bookname.get(position);
Toast.makeText(MainActivity.this, ""+booksdata.bookname, Toast.LENGTH_SHORT).show();
Intent intent=new Intent(MainActivity.this,Chapters.class);
intent.putExtra("booknumber",booksdata.booknumber);
intent.putExtra("bookname",booksdata.bookname);
startActivity(intent);
}
});
}
holder.cardView_title.setOnClickListener {
when (holder.tv_number.text) {
"1" -> {
(context as Activity).startActivity(Intent(context, Ma1::class.java))
}
"2" -> {
(context as Activity).startActivity(Intent(context, Ma2::class.java))
}
"3" -> {
(context as Activity).startActivity(Intent(context, Ma3::class.java))
}
}
}
I guess i'm implementing the spinner onItemSelected inappropriately.
So i have spinner values loaded from my database. I'm trying to load data according to the spinner selected but the spinner doesn't persist and the id doesn't pass to the activity. It loads a default id of 1 instead of the selected spinner id. So i'm not sure if the spinner id is being passed. How do i check these and correct them?
package com.example.app;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.firebase.messaging.FirebaseMessaging;
import com.example.app.Config;
import com.example.app.R;
import com.example.app.fragment.FragmentCategory;
import com.example.app.fragment.FragmentFavorite;
import com.example.app.fragment.FragmentProfile;
import com.example.app.fragment.FragmentRecent;
import com.example.app.fragment.FragmentVideo;
import com.example.app.models.Constituency;
import com.example.app.utils.AppBarLayoutBehavior;
import com.example.app.utils.Constant;
import com.example.app.utils.GDPR;
import com.squareup.picasso.Picasso;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
public class MainActivity extends AppCompatActivity {
String URL="https://xxx.xxx.xxx/api/get_constituency_index/?api_key="+
Config.API_KEY;
private long exitTime = 0;
MyApplication myApplication;
View view;
private BottomNavigationView navigation;
public ViewPager viewPager;
private Toolbar toolbar;
MenuItem prevMenuItem;
int pager_number = 5;
BroadcastReceiver broadcastReceiver;
Spinner mySpinner;
ArrayList<String> spinnerConstituencyName;
int spinConstID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set Font
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/Arkhip_font.ttf")
.setFontAttrId(R.attr.fontPath)
.build());
setContentView(R.layout.activity_main);
view = findViewById(android.R.id.content);
if (Config.ENABLE_RTL_MODE) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
}
}
AppBarLayout appBarLayout = findViewById(R.id.tab_appbar_layout);
((CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams()).setBehavior(new AppBarLayoutBehavior());
myApplication = MyApplication.getInstance();
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(R.string.app_name);
spinnerConstituencyName = new ArrayList<>();
mySpinner = findViewById(R.id.mySpinner);
loadSpinnerData(URL);
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
int check = 0;
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
/*String spinConstituency = mySpinner.getItemAtPosition(mySpinner.getSelectedItemPosition()).toString();
Toast.makeText(getApplicationContext(), spinConstituency, Toast.LENGTH_LONG).show();*/
if ( ++check > 1 ){
PrefManager prefManager = new PrefManager(MainActivity.this);
prefManager.writeString("" + spinConstID);
Intent intent = getIntent();
startActivity(intent);
Toast.makeText(getApplicationContext(), mySpinner.getItemAtPosition(mySpinner.getSelectedItemPosition()).toString() + " Showing", Toast.LENGTH_SHORT).show();
finish();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
viewPager = findViewById(R.id.viewpager);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
viewPager.setOffscreenPageLimit(pager_number);
navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
viewPager.setCurrentItem(0);
return true;
case R.id.navigation_category:
viewPager.setCurrentItem(1);
return true;
case R.id.navigation_video:
viewPager.setCurrentItem(2);
return true;
case R.id.navigation_favorite:
viewPager.setCurrentItem(3);
return true;
case R.id.navigation_profile:
viewPager.setCurrentItem(4);
return true;
}
return false;
}
});
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (prevMenuItem != null) {
prevMenuItem.setChecked(false);
} else {
navigation.getMenu().getItem(0).setChecked(false);
}
navigation.getMenu().getItem(position).setChecked(true);
prevMenuItem = navigation.getMenu().getItem(position);
if (viewPager.getCurrentItem() == 1) {
toolbar.setTitle(getResources().getString(R.string.title_nav_category));
} else if (viewPager.getCurrentItem() == 2) {
toolbar.setTitle(getResources().getString(R.string.title_nav_video));
} else if (viewPager.getCurrentItem() == 3) {
toolbar.setTitle(getResources().getString(R.string.title_nav_favorite));
} else if (viewPager.getCurrentItem() == 4) {
toolbar.setTitle(getResources().getString(R.string.title_nav_favorite));
} else {
toolbar.setTitle(R.string.app_name);
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
if (Config.ENABLE_RTL_MODE) {
viewPager.setRotationY(180);
}
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// checking for type intent filter
if (intent.getAction().equals(Constant.REGISTRATION_COMPLETE)) {
// now subscribe to global topic to receive app wide notifications
FirebaseMessaging.getInstance().subscribeToTopic(Constant.TOPIC_GLOBAL);
} else if (intent.getAction().equals(Constant.PUSH_NOTIFICATION)) {
// new push notification is received
String message = intent.getStringExtra("message");
Toast.makeText(getApplicationContext(), "Push notification: " + message, Toast.LENGTH_LONG).show();
}
}
};
Intent intent = getIntent();
final String message = intent.getStringExtra("message");
final String imageUrl = intent.getStringExtra("image");
final long nid = intent.getLongExtra("id", 0);
final String link = intent.getStringExtra("link");
if (message != null) {
LayoutInflater layoutInflaterAndroid = LayoutInflater.from(MainActivity.this);
View mView = layoutInflaterAndroid.inflate(R.layout.custom_dialog_notif, null);
final AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setView(mView);
final TextView notification_title = mView.findViewById(R.id.news_title);
final TextView notification_message = mView.findViewById(R.id.news_message);
final ImageView notification_image = mView.findViewById(R.id.news_image);
if (imageUrl.endsWith(".jpg") || imageUrl.endsWith(".jpeg") || imageUrl.endsWith(".png") || imageUrl.endsWith(".gif")) {
notification_title.setText(message);
notification_message.setVisibility(View.GONE);
Picasso.with(MainActivity.this)
.load(imageUrl.replace(" ", "%20"))
.placeholder(R.drawable.ic_thumbnail)
.resize(200, 200)
.centerCrop()
.into(notification_image);
alert.setPositiveButton(R.string.dialog_read_more, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(), ActivityNotificationDetail.class);
intent.putExtra("id", nid);
startActivity(intent);
}
});
alert.setNegativeButton(R.string.dialog_dismiss, null);
} else {
notification_title.setText(getResources().getString(R.string.app_name));
notification_message.setVisibility(View.VISIBLE);
notification_message.setText(message);
notification_image.setVisibility(View.GONE);
//Toast.makeText(getApplicationContext(), "link : " + link, Toast.LENGTH_SHORT).show();
if (!link.equals("")) {
alert.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent open = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
startActivity(open);
}
});
alert.setNegativeButton(R.string.dialog_dismiss, null);
} else {
alert.setPositiveButton(R.string.dialog_ok, null);
}
}
alert.setCancelable(false);
alert.show();
}
GDPR.updateConsentStatus(this);
}
public class MyAdapter extends FragmentPagerAdapter {
private MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new FragmentRecent();
case 1:
return new FragmentCategory();
case 2:
return new FragmentVideo();
case 3:
return new FragmentFavorite();
case 4:
return new FragmentProfile();
}
return null;
}
#Override
public int getCount() {
return pager_number;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.search:
Intent intent = new Intent(getApplicationContext(), ActivitySearch.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(menuItem);
}
}
#Override
public void onBackPressed() {
if (viewPager.getCurrentItem() != 0) {
viewPager.setCurrentItem((0), true);
} else {
exitApp();
}
}
public void exitApp() {
if ((System.currentTimeMillis() - exitTime) > 2000) {
Toast.makeText(this, getString(R.string.press_again_to_exit), Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
} else {
finish();
}
}
#Override
protected void onResume() {
super.onResume();
}
private int getIndex(Spinner spinner, String myString){
int index = 0;
for (int i=0;i<spinner.getCount();i++){
if (spinner.getItemAtPosition(i).equals(myString)){
index = i;
}
}
return index;
}
private void loadSpinnerData(String url) {
RequestQueue requestQueue=Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONObject jsonObject=new JSONObject(response);
if(jsonObject.getString("status").equals("ok")){
JSONArray jsonArray=jsonObject.getJSONArray("constituencies");
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject1=jsonArray.getJSONObject(i);
String spinConstituency=jsonObject1.getString("constituency_name");
spinConstID = jsonObject1.getInt("const_id");
spinnerConstituencyName.add(spinConstituency);
}
}
ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(MainActivity.this,
R.layout.custom_spinner_item, spinnerConstituencyName){
#Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
View view = super.getDropDownView(position, convertView, parent);
TextView tv = (TextView) view;
if(position%2 == 1) {
// Set the item background color
tv.setBackgroundColor(Color.parseColor("#910D3F"));
}
else {
// Set the alternate item background color
tv.setBackgroundColor(Color.parseColor("#41061C"));
}
return view;
}
};
mySpinner.setPrompt("Select Your Constituency");
myAdapter.setDropDownViewResource(R.layout.custom_spinner_item);
mySpinner.setAdapter(myAdapter);
//RECEIVE DATA VIA INTENT
Intent i = getIntent();
String name = i.getStringExtra("NAME_KEY");
mySpinner.setSelection(getIndex(mySpinner, name));
}catch (JSONException e){e.printStackTrace();}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
int socketTimeout = 30000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
requestQueue.add(stringRequest);
}
}
Here is the problem (On Spinner Item selection)
Intent intent = getIntent();
startActivity(intent);
Toast.makeText(getApplicationContext(), mySpinner.getItemAtPosition(mySpinner.getSelectedItemPosition()).toString() + " Showing", Toast.LENGTH_SHORT).show();
finish();
**You are starting current activity as new and finish current activity, it means when you select any of items from spinner it will start a new activity and your on create executed again and again, so please place other logic or you can send your values in your activity using intent.putextra() and check in oncreate for null and if values is not null you can set spinner.setSelected(Your Position). For Fragment You can use
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(ComingSoonFragment.this).attach(ComingSoonFragment.this).commit();
for refresh your fragment and pass your data with bundle and check for null if your bundle is null then use your code for defalt and if not null then set your data according to your id.
**
Thanks
In your spinner inside OnItemSelectedListener use parent.getItemAtPosition(position) to get the correct value
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(position).toString(),
Toast.LENGTH_SHORT).show();
//Do your staff here
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
I'm having an issue passing an array into a listview
I can pass an image to the second activty but when I
try to pass an array to the listview I get a lang.NullPointerException error
and the app crashes.
any helpful input would be great Thanks
here is the code
Main Activity
package com.example.androidlistview;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
public class MainActivity extends Activity {
ListView listView;
// Defined the text values to show in ListView
String[] values = new String[]{"Barack Obama","Donald Trump","Bill Clinton",
"Hillary Clinton","Joe Biden"};
// Defined the image ids to show in ListView
Integer[] images = {
R.drawable.image1,R.drawable.image2,R.drawable.image3,R.drawable.image4,
R.drawable.image5
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// create the custom view
CustomView adapter = new CustomView(MainActivity.this, values, images);
// Get ListView object from xml
listView = (ListView) findViewById(R.id.container);
//set adapter
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
if(position == 0){
Intent contact = new Intent(MainActivity.this, Details.class);
String[] details= new String[]{"Barack Obama","The White House","1-234-567-8900",
"Barack.Obama#whitehouse.com","note"};
Integer image = images[0];
contact.putExtra("image", image);
contact.putExtra("details", details);
startActivity(contact);
}
if(position == 1){
Intent contact = new Intent(MainActivity.this, Details.class);
String[] details= new String[] {"Donald Trump","Trump Tower","1-234-567-8901",
"Donald.Trump#whitehouse.com","note"};
Integer image = images[1];
contact.putExtra("image", image);
contact.putExtra("details", details);
startActivity(contact);
}
if(position == 2){
Intent contact = new Intent(MainActivity.this, Details.class);
String[] details = new String[] {"Bill Clinton","New York","1-234-567-8902",
"Bill.Clinton#whitehouse.com","note"};
Integer image = images[2];
contact.putExtra("image", image);
contact.putExtra("details", details);
startActivity(contact);
}
if(position == 3){
Intent contact = new Intent(MainActivity.this, Details.class);
String[] details = new String[] {"Hillary Clinton","New Jersey","1-234-567-8903",
"Hillary.Clinton#whitehouse.com","note"};
Integer image = images[3];
contact.putExtra("image", image);
contact.putExtra("details", details);
startActivity(contact);
}
if(position == 4){
Intent contact = new Intent(MainActivity.this, Details.class);
String[] details= new String[] {"Joe Biden","OHIO","1-234-567-8903",
"Joe.Biden#whitehouse.com","note"};
Integer image = images[4];
contact.putExtra("image", image);
contact.putExtra("details", details);
startActivity(contact);
}
}
});
}
}
Second Activity I want to pass the array to
package com.example.androidlistview;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Details extends Activity {
ListView list;
String []web={"Name:","Address:","Phone Number:","Email:","Note:"};
int image;
String[] details;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
// create the custom view
CustomList Adapter= new CustomList(Details.this, web, details);//, details should go here
// Get ListView object from xml
list=(ListView)findViewById(R.id.list);
//set adapter
list.setAdapter(Adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
}
});
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
image= bundle.getInt("image");
ImageView imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setImageResource(image);
}
}
}
and the custom view i'm using for the Second Activity details
package com.example.androidlistview;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class CustomList extends ArrayAdapter<String>{
private final Activity mContext;
private final String[] web;
private final String[] details;
public CustomList(Activity mContext,String[] web, String[] details){ //, String[] details should go here
super(mContext, R.layout.list_single, web);
this.mContext=mContext;
this.web=web;
this.details=details;
}
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = mContext.getLayoutInflater();
View rowView= inflater.inflate(R.layout.list_single, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
txtTitle.setText(web[position]);
TextView txtTitle1 = (TextView)rowView.findViewById(R.id.txt1);
txtTitle1.setText(details[position]);
return rowView;
}
}
This is what i did to fix this
Main Activity
package com.example.androidcontacts;
import android.app.ListActivity;
import android.content.CursorLoader;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.CursorAdapter;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SimpleCursorAdapter;
public class MainActivity extends ListActivity {
ListView mylist;
SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Uri allContacts = Uri.parse("content://"+"com.example.androidcontacts.Books" + "/Contact");
Cursor c;
CursorLoader cursorLoader = new CursorLoader(
this,allContacts,null,null,null,null);
c = cursorLoader.loadInBackground();
String[] columns = new String[] {Contact._ID,Contact.TITLE,Contact.AUTHOR,Contact.YEAR,Contact.IMAGE};
int[] views = new int[] {R.id.contactID,R.id.contactName,R.id.contactAuthor,R.id.contactYear,R.id.Image};
SimpleCursorAdapter adapter;
adapter = new SimpleCursorAdapter(this, R.layout.activity_main,
c, columns, views,CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
this.setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView list, View view, int position, long id) {
//Intent i=new Intent(MainActivity.this,Details.class);
//startActivity(i);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
if(id == R.id.action_search){
Intent intent = new Intent(this, Search.class);
startActivity(intent);
finish();
return true;
}
if(id == R.id.action_add){
Intent intent = new Intent(this, Add.class);
startActivity(intent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Second activity Details
package com.example.androidlistview;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class Details extends Activity {
//Variables for Bundle
int image;
String name;
String address;
String phone;
String email;
String note;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
Button SMS = (Button) findViewById(R.id.button1);
SMS.setOnClickListener(new OnClickListener() {
//when button1 is clicked open messenger
#Override
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", phone, null)));
}
});
Button Email = (Button) findViewById(R.id.button2);
Email.setOnClickListener(new OnClickListener() {
//when button2 is clicked open email
#Override
public void onClick(View v) {
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:"));
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { email });
startActivity(Intent.createChooser(emailIntent, "Choose Email Client"));
}
});
Button Phone = (Button) findViewById(R.id.button3);
Phone.setOnClickListener(new OnClickListener() {
//when button3 is clicked start call
#Override
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", phone, null)));
}
});
// get details passed from MainActivity
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
image= bundle.getInt("image");
ImageView imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setImageResource(image);
name = bundle.getString("name");
TextView nameView = (TextView) findViewById(R.id.name1);
nameView.setText(name);
address = bundle.getString("address");
TextView addressView = (TextView) findViewById(R.id.address1);
addressView.setText(address);
phone = bundle.getString("phone");
TextView phoneView = (TextView) findViewById(R.id.phone1);
phoneView.setText(phone);
email = bundle.getString("email");
TextView emailView = (TextView) findViewById(R.id.email1);
emailView.setText(email);
note = bundle.getString("note");
TextView noteView = (TextView) findViewById(R.id.note1);
noteView.setText(note);
}
}
}
My Custom View
package com.example.androidlistview;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomView extends ArrayAdapter<String>{
private final Activity context;
private final String[] values;
private final Integer[] images;
//Constructor
public CustomView(Activity context,String[] values, Integer[] images) {
super(context, R.layout.single_row, values);
this.context = context;
this.values = values;
this.images = images;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.single_row, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
txtTitle.setText(values[position]);
ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
imageView.setImageResource(images[position]);
return rowView;
}
}