I am passing value as string from an activity through intent to this Page Activity and adding it to an arraylist and setting that list to an list view using base adapter.But unfortunately its the values are not showing in listview.
And I am not able to figure out how to set that value to the textview present in PagesAdapter.java.
Please help me guys.
Pages.java
public class Pages extends Activity implements AdapterView.OnItemClickListener {
private static final String TAG = null;
private List<String> list = new ArrayList<>();
private ListView listView;
private PagesAdapter pageadapter;
private String androidOS;
private String device_uuid;
private String contributor_id;
public String tocName;
public String categoryName;
private SessionManager session;
private String first_Page;
private String last_Page;
private String current_Page;
private String firstPage;
private String lastPage;
private String currentPage;
ProgressDialog loading;
private String page;
private String name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pages);
listView = (ListView) findViewById(R.id.list);
listView.setOnItemClickListener(this);
page = getIntent().getExtras().getString("CONTENT");
name = getIntent().getExtras().getString("NAME");
session = new SessionManager(getApplicationContext());
SharedPreferences pref = this.getSharedPreferences("preferences", 0);
firstPage = pref.getString("firstpage",null);
lastPage = pref.getString("lastpage",null);
currentPage = pref.getString("currentpage",null);
contributor_id = pref.getString("contributor_id",null);
loading = ProgressDialog.show(this,"Loading Data", "Please wait...",false,false);
//getData();
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
androidOS = Build.VERSION.RELEASE;
device_uuid = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
list.add(name);
pageadapter = new PagesAdapter(Pages.this, list);
listView.setAdapter(pageadapter);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(Pages.this, RecordComposition.class);
i.putExtra("PAGE",page);
startActivity(i);
}
}
PagesAdapter.java
public class PagesAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<String> Pagelist;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public PagesAdapter(Activity activity, List<String> billionairesItems) {
this.activity = activity;
this.Pagelist = billionairesItems;
}
#Override
public int getCount() {
return Pagelist.size();
}
#Override
public Object getItem(int location) {
return Pagelist.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.pages_view, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.thumbnail);
TextView name = (TextView) convertView.findViewById(R.id.name);
// String m = Pagelist.get(position);
// thumbNail.setImageUrl(m.getImage(), imageLoader);
// name.setText(m.get);
return convertView;
}
}
You have to set value to the textView :
TextView name = (TextView) convertView.findViewById(R.id.name);
name.setText(Pagelist.get(position));
The first problem is related to your list variable. You are passing it as a Empty List, because you are not populating it with String values.
The adapter will scan your list and verify that there is no data to display, so try to put some data inside the list variable and test the ListView again.
The second question is easy to resolve, just add these lines inside your getView method:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView name = (TextView) convertView.findViewById(R.id.name);
name.setText(Pagelist.get(position));
}
Related
I'm trying to make and activity that uses fragment with viewpager2 and I'm having problem populating the grid view inside the viewpage2. and I'm having trouble using adapters. what are the steps I need to know to make this activity work?
this is my fragment class
public class item_frag extends Fragment{
Context context;
FragmentItemDisplayBinding binding;
String name, description, category, price, imageurl;
FirebaseStorage firebaseStorage;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("inventory");
firebaseStorage = FirebaseStorage.getInstance();
name = databaseReference.getDatabase().getReference("inventory").toString();
description = databaseReference.getDatabase().getReference("inventory").toString();
category = databaseReference.getDatabase().getReference("inventory").toString();
price = databaseReference.getDatabase().getReference("inventory").toString();
imageurl = firebaseStorage.getReference("inventory").toString();
String[] itemname = {"hello"};
int[] itemimage = {R.drawable.unimas_logo};
View view = inflater.inflate(R.layout.fragment_item_display, container, false);
GridView gridView = (GridView) view.findViewById(R.id.grid_view);
item_frag_adapter itemFragAdapter = new item_frag_adapter(context, itemname, itemimage);
gridView.setAdapter(itemFragAdapter);
return inflater.inflate(R.layout.fragment_item_display, container, false);
}
}
this is my item fragment adapter class
public class item_frag_adapter extends BaseAdapter {
Context context;
String[] itemname;
int[] image;
LayoutInflater inflater;
public item_frag_adapter(Context context, String[] itemname, int[] image) {
this.context = context;
this.itemname = itemname;
this.image = image;
}
#Override
public int getCount() {
return itemname.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null){
convertView = inflater.inflate(R.layout.item_card,null);
}
ImageView imageView = convertView.findViewById(R.id.idIVimage);
TextView textView = convertView.findViewById(R.id.idTVtext);
imageView.setImageResource(image[position]);
textView.setText(itemname[position]);
return convertView;
}
}
I am an intern at this company and I have a task assigned to me by my team leader where I need to make an app that displays a list of items that I can add to and edit/delete the items on the list. I am following the requirements given to me on what the app needs to do.
The problem I'm having is that I need to pass values from an item when clicked on a ListView which uses a custom adapter, and have them sent to a new activity and displayed on the new activity's textviews and imageview. I have tried using putExtras() methods in the list click method and getting the values using getExtras() methods but they didn't work and I've already deleted those codes, so they are no longer there. If you need more of the classes/activities I'm using please let me know. I am using Android Studio 3.1.4
ItemListView.java
public class ItemListView extends AppCompatActivity {
DatabaseHelper myDB;
ArrayList<Item> itemList;
ListView listView;
Item item;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_list_view);
listView = (ListView) findViewById(R.id.listView);
myDB = new DatabaseHelper(this);
itemList = new ArrayList<>();
Cursor data = myDB.getListContents();
int numRows = data.getCount();
if(numRows == 0){
Toast.makeText(ItemListView.this, "There is nothing in the database.", Toast.LENGTH_LONG).show();
} else {
while(data.moveToNext()){
item = new Item(data.getString(1), data.getString(2), data.getString(3));
itemList.add(item);
}
Row_ListAdapter adapter = new Row_ListAdapter(this, R.layout.list_adapter_view, itemList);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(ItemListView.this, ViewItemClicked.class);
startActivity(intent);
}
});
}
ViewItemClicked.java
I want the values displayed onto the layout of this activity when a row is clicked.
public class ViewItemClicked extends AppCompatActivity {
ImageView image;
TextView name, desc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_item_clicked);
}
}
Other classes I used:
Row_ListAdapter.java
public class Row_ListAdapter extends ArrayAdapter<Item> {
private LayoutInflater mInflater;
private ArrayList<Item> items;
private int mViewResourceId;
ImageView image;
TextView name;
TextView description;
public Row_ListAdapter(Context context, int textViewResourceId, ArrayList<Item> items){
super(context, textViewResourceId, items);
this.items = items;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mViewResourceId = textViewResourceId;
}
public View getView(int position, View convertView, ViewGroup parents){
convertView = mInflater.inflate(mViewResourceId, null);
Item item = items.get(position);
if(item != null){
image = (ImageView) convertView.findViewById(R.id.iconIV);
name = (TextView) convertView.findViewById(R.id.nameTV);
description = (TextView) convertView.findViewById(R.id.descTV);
if(image != null){
image.setImageBitmap(item.getImage());
}
if(name != null){
name.setText(item.getName());
}
if(description != null){
description.setText(item.getDescription());
}
}
return convertView;
}
}
Link to GUI: https://i.stack.imgur.com/wHfgv.png
Before you pass the data, implement your Item Class with Serializable like this:
public class Item implements Serializable{
/*your class code here*/
}
Then pass the data in the listView.setOnItemClicklistener like this
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Item passItem = itemList.get(position);
Intent intent = new Intent(ItemListView.this, ViewItemClicked.class);
Bundle itemBundle = new Bundle();
itemBundle.putSerializable("dataItem",passItem)// put the data and define the key
intent.putExtras(itemBundle)
startActivity(intent);
}
});
and to open the data in the ViewItemClicked.Class
public class ViewItemClicked extends AppCompatActivity {
ImageView image;
TextView name, desc;
Item item;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
item = (Item) getIntent().getSerializableExtra("dataItem"); // use the key
setContentView(R.layout.activity_view_item_clicked);
/*now u can use the item data*/
}
}
Try the codes below:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(ItemListView.this, ViewItemClicked.class);
String name = itemList.get(position).getString(1);
String description = itemList.get(position).getString(2);
String something_else = itemList.get(position).getString(3);
intent.putExtra("name", name);
intent.putExtra("description", description);
intent.putExtra("something_else", something_else);
startActivity(intent);
}
In your Details Activity:
Intent intent = getIntent();
String name = intent.getStringExtra("name");
String description = intent.getStringExtra("description");
String something_else = intent.getStringExtra("something_else");
Now use the strings to show the values in the desired places.
as
edittext.setText(name);
WHAT FORMAT TYPE OF IMAGE YOUR ARE USING
Is it Base64 or Bitmap if it is Base64 try this code..
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(ItemListView.this, ViewItemClicked.class);
String name = list.get(position).getName();
String description = list.get(position).getDescription();
String image= list.get(position).getImage();
startActivity(intent);
}
In Your Second Activity use this code..
Intent intent = getIntent();
String name = intent.getStringExtra("name");
String description = intent.getStringExtra("description");
String image = intent.getStringExtra("image");
Convert here Base64 to Bitmap..
byte[] decodedString = Base64.decode(image, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0,
decodedString.length);
Define an interface for listening item click event
public class Row_ListAdapter extends ArrayAdapter<Item> {
private LayoutInflater mInflater;
private ArrayList<Item> items;
private int mViewResourceId;
ImageView image;
TextView name;
TextView description;
OnItemListener mListener;
public Row_ListAdapter(Context context, int textViewResourceId, ArrayList<Item> items){
super(context, textViewResourceId, items);
this.items = items;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mViewResourceId = textViewResourceId;
}
public View getView(int position, View convertView, ViewGroup parents){
convertView = mInflater.inflate(mViewResourceId, null);
Item item = items.get(position);
if(item != null){
image = (ImageView) convertView.findViewById(R.id.iconIV);
name = (TextView) convertView.findViewById(R.id.nameTV);
description = (TextView) convertView.findViewById(R.id.descTV);
if(image != null){
image.setImageBitmap(item.getImage());
}
if(name != null){
name.setText(item.getName());
}
if(description != null){
description.setText(item.getDescription());
}
}
convertView.setOnClickListener((v) -> {
if(mListener != null) {
mListener.onItemClick(v, item);
}
})
return convertView;
}
public void setOnItemListener(OnItemListener listener) {
mListener = listener;
}
public interface OnItemClickListener {
void onItemClick(View v, Item item);
}
}
Then, implement OnItemClickListener in the activity and set it to the adapter:
Row_ListAdapter adapter = new Row_ListAdapter(this, R.layout.list_adapter_view, itemList);
adapter.setOnItemListener("your implement");
I am creating an app in android studio.
I need to update the list view with a new url that is sent via text message.
How do I add the new url to my list?
This is what I currently have for my main code.
public class MainActivity extends AppCompatActivity {
ListView list;
WebView webView;
ArrayList<String> sites = new ArrayList<>("https://www.google.com", "https://www.yahoo.com", "https://www.apple.com");
String [] url = {"https://www.google.com", "https://www.yahoo.com", "https://www.apple.com"};
MyBroadcastReceiver receiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView)findViewById(R.id.listview);
MyListAdapter adapter = new MyListAdapter(this, sites);
sites.add("new site");
adapter.notifyDataSetChanged();
list.setAdapter(adapter);
list.setDividerHeight(5);
webView = (WebView)findViewById(R.id.webview);
webView.setWebViewClient(new WebViewClient(){});
list.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id){
Toast.makeText(getApplicationContext(), sites.get(position), Toast.LENGTH_SHORT).show();
webView.loadUrl("https://www.google.com");
webView.loadUrl(url[position]);
}
});
receiver = new MyBroadcastReceiver();
IntentFilter filter = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
registerReceiver(receiver,filter);
}
}
This is myAdapterList:
public class MyListAdapter extends ArrayAdapter<String> {
private Activity context_;
private ArrayList<String> sites;
//constructor
public MyListAdapter(Activity context, ArrayList<String> sites){
super(context,R.layout.row,sites);
context_ = context;
this.sites = sites;
}
public View getView (int position, View convertView, ViewGroup parent){
if(convertView == null){
LayoutInflater inflater = context_.getLayoutInflater();
convertView = inflater.inflate(R.layout.row,null);
}
ViewHolder holder = (ViewHolder) convertView.getTag();
if(holder == null){
holder = new ViewHolder(convertView);
holder.tv_link.setText(sites.get(position));
}
else{
holder.tv_link.setText(sites.get(position));
}
return convertView;
}
private class ViewHolder{
TextView tv_link;
public ViewHolder(View row){
tv_link = (TextView) row.findViewById(R.id.tv_link);
}
}
}
Right now I use setAdapter to update my ListView, but I think the proper way is to use notifiyDatasetChanged() and I can't get that to work in my main class (it's in the adapter). Here is the error:
The method notifyDatasetChanged() is undefined for the type ListAdapter
I'm guessing there is a better way of doing this - can anyone point me in the right direction?
Here's the relevant parts of my code:
public class ScoreList extends SherlockFragmentActivity {
private ListView listViewScore;
static List<Score> listScore = new ArrayList<Score>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.score_list);
ctx = this;
listScore = dbh.getAllScores();
listViewScore = (ListView) findViewById(R.id.score_list);
listViewScore.setAdapter(new ScoreListAdapter(ctx,
R.layout.score_row_item, listScore));
listViewScore.getAdapter().notifyDatasetChanged(); //this is where I get the error
}
}
Here's the adapter:
public class ScoreListAdapter extends ArrayAdapter<Score> {
private int resource;
private LayoutInflater inflater;
public ScoreListAdapter(Context ctx, int resourceId, List<Score> objects) {
super(ctx, resourceId, objects);
resource = resourceId;
inflater = LayoutInflater.from(ctx);
//context = ctx;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
convertView = (LinearLayout) inflater.inflate(resource, null);
Score score = getItem(position);
TextView txtName = (TextView) convertView.findViewById(R.id.name);
txtName.setText(score.getName());
TextView txtScoreChange = (TextView) convertView
.findViewById(R.id.scoreChange);
int scoreChange = Integer.parseInt(score.getScoreChange());
if (scoreChange > 0)
txtScoreChange.setText("+" + scoreChange);
else if (scoreChange < 0)
txtScoreChange.setText("" + scoreChange);
else
txtScoreChange.setText("");
TextView txtScoreTotal = (TextView) convertView
.findViewById(R.id.scoreTotal);
txtScoreTotal.setText(score.getScoreTotal());
final LinearLayout currentRow = (LinearLayout) convertView
.findViewById(R.id.scoreRowLayout);
notifyDataSetChanged();
return convertView;
}
}
Create an instance of your custom adapter, so you can use it anywhere you like...
public class ScoreList extends SherlockFragmentActivity {
private ListView listViewScore;
private ScoreListAdapter adapter;
static List<Score> listScore = new ArrayList<Score>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.score_list);
ctx = this;
listScore = dbh.getAllScores();
listViewScore = (ListView) findViewById(R.id.score_list);
adapter = new ScoreListAdapter(ctx, R.layout.score_row_item, listScore);
listViewScore.setAdapter(adapter);
adapter.notifyDatasetChanged();
}
}
By the way, if your listScore array is already loaded, then you do not need to use
adapter.notifyDatasetChanged();
Dont call the notifyDataSetChanged(); method while creation.
only call it when content of your listViewScore changes.. and to use it at that time-
replace
listView.getAdapter().notifyDatasetChanged();
with
((ScoreListAdapter)listView.getAdapter()).notifyDataSetChanged();
and see the magic...
thanks.
I am required to create a project similar to that of the ff. pic. (My apologies for the use a siily pic, I have to make do with what is readily-available).
I wouldn't say what I did was the best approach in making a 'dynamic' ListView but I'd be glad just to make what I currently have work. Anyway my implementation is as follows:
public class MultiLineListViewActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<SearchResults> searchResults = getSearchResults();
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(new MyCustomBaseAdapter(this, searchResults));
}
private ArrayList<SearchResults> getSearchResults() {
ArrayList<SearchResults> results = new ArrayList<SearchResults>();
SearchResults sr1 = new SearchResults();
sr1.setName("Name 1");
sr1.setPhone("12345");
SearchResults.setIcon(R.drawable.pic_one);
results.add(sr1);
sr1 = new SearchResults();
sr1.setName("Name 2");
sr1.setPhone("123456");
SearchResults.setIcon(R.drawable.pic_two);
results.add(sr1);
...
return results;
}
}
public class SearchResults {
private String name;
private String phone;
public static ArrayList<Integer> iconsList = new ArrayList<Integer>();
public void setName(String name) {
this.name = name;
}
public void setPhone(String phone) {
this.phone = phone;
}
public static void setIcon(int i) {
iconsList.add(i);
}
public String getName() {
return this.name;
}
public String getPhone() {
return this.phone;
}
}
public class MyCustomBaseAdapter extends BaseAdapter {
private ArrayList<SearchResults> searchArrayList;
private LayoutInflater layoutInflater;
private Context context;
public MyCustomBaseAdapter(Context context, ArrayList<SearchResults> results) {
this.searchArrayList = results;
//this.context = context;
layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return searchArrayList.size();
}
#Override
public Object getItem(int position) {
return searchArrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
ImageView imageView;
if(convertView == null) {
convertView = layoutInflater.inflate(R.layout.custom_row_view, null);
holder = new ViewHolder();
holder.txtName = (TextView) convertView.findViewById(R.id.name);
holder.txtPhone = (TextView) convertView.findViewById(R.id.phone);
imageView = new ImageView(context);
convertView.setTag(holder);
}
else {
//imageView = (ImageView) convertView;
holder = (ViewHolder) convertView.getTag();
}
imageView = new ImageView(context);
imageView.setImageResource(SearchResults.iconsList.get(position));
holder.txtName.setText(searchArrayList.get(position).getName());
holder.txtPhone.setText(searchArrayList.get(position).getPhone());
return convertView;
}
class ViewHolder {
TextView txtName;
TextView txtPhone;
}
The above code was successful in displaying the Name and Phone lines in the ListView, it's the addition of the image that's giving me the 'Force Close'.
Take note of the commented line imageView = (ImageView) convertView;
I have reduced it down to that particular line in that removing the comments causes the app to crash.
Note: Whenever you get a force close that you're asking about in a StackOverflow question, please post the full stack trace.
You're always creating a new ImageView when in fact you probably shouldn't need to create one at all. It should be defined in your custom item layout (which you should probably post as well in this case) just like the TextViews. You can use findViewById the same way and get it.
kabuko is right on both counts. (UPDATE: also his comment below should not be ignored.) I'm guessing that your layout/custom_row_view is a LinearLayout, which would mean that the commented line attempts to coerce a LinearLayout to an ImageView, which yes would raise an exception. Also, your ViewHolder class is superfluous, just define those TextViews as variables in your getView() like so...
// Assuming that layout/custom_row_view is a LinearLayout...
getView(yadda) {
LinearLayout row;
ImageView imageView;
TextView txtName, txtPhone;
if (convertView == null) {
row = // inflate a new one
} else {
row = // get the old one
}
// fetch the views
imageView = row.findViewById(...);
txtName = row.findViewById(...);
txtPhone = row.findViewById(...);
// fill the views
imageView.setImageResource(...);
txtName.setContent(...);
txtPhone.setContent(...);
return row;
}
Ciao.