I know to get the ListItem from:
string[] = {"data1","data","data3"};
But how do I get it from a JSON response? I moved my data to:
ArrayList<HashMap<String, String>>
My code is below, I have to use JSON instead of getting a String[] because my JSON response contains an id, a title and an image link.
public class MainActivity extends AppCompatActivity {
String[] titles,header;
ListView list1;
int[] img;
String[] title;
int[] img = {R.drawable.img1, R.drawable.img2,R.drawable.img3};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list1 = (ListView) findViewById(R.id.list);
title ={"data1","data2","data3"}
myAdapter adapter = new myAdapter(getApplicationContext(), titles, img);
list1.setAdapter(adapter);
}
class myAdapter extends ArrayAdapter<String> {
Context context;
int[] imgs;
String[] titles;
private ArrayList<String> mData = new ArrayList<>();
private ArrayList<Integer> mImage = new ArrayList<>();
private TreeSet<Integer> sectionHeader = new TreeSet<Integer>();
private LayoutInflater mInflater;
myAdapter(Context context, String[] titles, int imgs[]) {
super(context, R.layout.list_item, R.id.text, titles);
this.context = context;
this.imgs = imgs;
this.titles = titles;
mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int rowType = getItemViewType(position);
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.list_item, parent, false);
holder.myImage = (ImageView) convertView.findViewById(R.id.image);
holder.myText = (TextView) convertView.findViewById(R.id.texttitle);
Picasso.with(context)
.load(imgs[position])
.fit()
.into(holder.myImage);
holder.myText.setText(titles[position]);
convertView.setTag(holder.myImage);
return convertView;
}
public class ViewHolder {
public TextView myText;
public ImageView myImage;
}
}
}
First change your above code by below so that you can see the list of image and string properly:
public class MainActivity extends AppCompatActivity {
ListView list1;
String[] title = {"data1", "data2", "data3"};
;
int[] img = {R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list1 = (ListView) findViewById(R.id.list);
myAdapter adapter = new myAdapter(getApplicationContext(), title, img);
list1.setAdapter(adapter);
}
}
class myAdapter extends ArrayAdapter<String> {
Context context;
int[] imgs;
String[] titles;
private ArrayList<String> mData = new ArrayList<>();
private ArrayList<Integer> mImage = new ArrayList<>();
private TreeSet<Integer> sectionHeader = new TreeSet<Integer>();
private LayoutInflater mInflater;
myAdapter(Context context, String[] titles, int imgs[]) {
super(context, R.layout.list_item, R.id.text, titles);
this.context = context;
this.imgs = imgs;
this.titles = titles;
mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int rowType = getItemViewType(position);
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.list_item, parent, false);
holder.myImage = (ImageView) convertView.findViewById(R.id.image);
holder.myText = (TextView) convertView.findViewById(R.id.texttitle);
holder.myImage.setImageResource(imgs[position]);
// Picasso.with(context)
// .load(imgs[position])
// .fit()
// .into(holder.myImage);
holder.myText.setText(titles[position]);
convertView.setTag(holder.myImage);
}
return convertView;
}
public class ViewHolder {
public TextView myText;
public ImageView myImage;
}
}
Related
I have tried adding the adapter in the onCreate() as well and it throws a null pointer exception with an error 'Attempt to invoke listVIew.setAdapter on a null object reference.
Here is the code where I use notifyDataSetChange() inside my Main Activity;
import static com.name.sample.Tab1.adapter;
public class Requests extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
Cursor c = myDB.rawQuery("SELECT * FROM requests", null);
int aIndex = c.getColumnIndex("name");
int bIndex = c.getColumnIndex("nick");
int cIndex = c.getColumnIndex("num");
name.clear();
nick.clear();
number.clear();
if (c.moveToFirst()){
do {
name.add(c.getString(aIndex));
nick.add(c.getString(bIndex));
number.add(c.getInt(cIndex));
} while (c.moveToNext());
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
adapter.notifyDataSetChanged();
}
}
Here is my Tab1 code
Here is the code for the Adapter
public class Tab1 extends Fragment {
static ListView listNotifications;
final static ArrayList<String> name = new ArrayList<>();
static ArrayList<Integer> number = new ArrayList<>();
static ArrayList<String> nick = new ArrayList<>();
static ImageAdapter adapter;
public static class ImageAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public ImageAdapter (Context context, String[] values) {
super(context, R.layout.list_with_icons, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.list_with_icons, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.textViewName);
ImageView imageView = (ImageView) rowView.findViewById(R.id.imagePicture);
textView.setText(values[position]);
// Change the icon for Windows and iPhone
return rowView;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab1layout, container, false);
String[] nameString = new String[name.size()];
nameString = name.toArray(nameString);
adapter = new ImageAdapter (getActivity(), nameString);
listNotifications =(ListView)rootView.findViewById(R.id.listNotifications);
listNotifications.setAdapter(adapter);
return rootView;
}}
Try using: adapterClass.this.notifyDataSetChanged() in onPostExcecute()
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
InvitedAdapter.this.notifyDataSetChanged();
}
you have added a wrong adapter in the listview. it should be like this in onCreateView():
listNotifications.setAdapter(adapter);
Try this :)
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);
}
}
}
i'm trying to develop an android app. i used Custom listview for array.
i have 4 buttons like that :
But i want to that : When Yellow button clicked listview's style :
When Button 2 clicked listview's style : :
My codes below :
CustomTextview xml:
android:background="#drawable/lstx_1"
android:id="#+id/ls_txt"
android:textSize="20dp"
android:textAlignment="center"
android:textColor="#ffffff"
android:layout_width="match_parent"
android:layout_height="40dp"/>
CustomAdapter.java
public class customlist extends ArrayAdapter<String> {
private final Activity context;
private final String[] hikayeler;
private Typeface tf;
public customlist(Activity context, String[] hikayeler) {
super(context,R.layout.lsv_txt, hikayeler);
this.context = context;
this.hikayeler = hikayeler;
this.tf = Typeface.createFromAsset(context.getAssets(), "poetsen.ttf");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.lsv_txt, null, true);
TextView ls_txt = (TextView) rowView.findViewById(R.id.ls_txt);
ls_txt.setText(hikayeler[position]);
ls_txt.setTypeface(tf);
GradientDrawable gdBaslik = new GradientDrawable();
gdBaslik.setColor(Color.parseColor("#cf96ac"));
gdBaslik.setCornerRadius(12);
gdBaslik.setStroke(2, Color.parseColor("#cf96ac"));
ls_txt.setBackground(gdBaslik);
return rowView;} }
The sample code is as follows:
private ListView mListView;
private customlist mcustomAdapter;
private boolean mStyle = false;
public void showColor(View v) {
if (mListView == null) {
mListView = (ListView) findViewById(R.id.lv_test);
mcustomAdapter = new customlist(this, new String[] { "aaaa", "bbbbb", "ccccc" });
mListView.setAdapter(mcustomAdapter);
} else {
GradientDrawable gdBaslik = new GradientDrawable();
if (mStyle) {
gdBaslik.setColor(Color.parseColor("#cf96ac"));
gdBaslik.setCornerRadius(12);
gdBaslik.setStroke(2, Color.parseColor("#cf96ac"));
} else {
gdBaslik.setColor(Color.parseColor("#849232"));
gdBaslik.setCornerRadius(12);
gdBaslik.setStroke(2, Color.parseColor("#849232"));
}
mStyle = !mStyle;
mcustomAdapter.setGradientDrawable(gdBaslik);
}
}
public class customlist extends ArrayAdapter<String> {
private final Activity context;
private final String[] hikayeler;
private GradientDrawable gdBaslik;
private Typeface tf;
public customlist(Activity context, String[] hikayeler) {
super(context, R.layout.lsv_txt, hikayeler);
this.context = context;
this.hikayeler = hikayeler;
this.tf = Typeface.createFromAsset(context.getAssets(), "poetsen.ttf");
}
public void setGradientDrawable(GradientDrawable drawable) {
this.gdBaslik = drawable;
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.lsv_txt, null, true);
TextView ls_txt = (TextView) rowView.findViewById(R.id.ls_txt);
ls_txt.setText(hikayeler[position]);
ls_txt.setTypeface(tf);
ls_txt.setBackground(gdBaslik);
return rowView;
}
}
Note: "showColor(View v)" is a Button click event.I hope it can help you.
Sorry for my english. I use SlideMenu libruary and i want use new font for textview, it old version use:
((ListView) ((Activity) context).findViewById(R.id.sidemenulistobject)).setAdapter(
new ArrayAdapter<Object>(
context,
R.layout.sidemenu_item,
R.id.textSlide,
items
)
);
But this i cant get my textSlide and set new font. Now i add array adapter and set this in listView. This is my all code:
menu = new SlidingMenu(context);
menu.setMode(SlidingMenu.LEFT);
menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
menu.setShadowWidth(15);
menu.setFadeDegree(1.0f);
menu.setShadowWidthRes(R.dimen.shadow_width);
menu.setShadowDrawable(R.drawable.shadow);
menu.attachToActivity((Activity) context, SlidingMenu.SLIDING_WINDOW);
menu.setBehindWidth(400);
menu.setMenu(R.layout.sidemenu);
//add item in list view
ArrayList<String> itemsObj = new ArrayList<String>();
itemsObj.add("Новости");
itemsObj.add("События");
itemsObj.add("Наше меню");
itemsObj.add("Фотографии");
itemsObj.add("Видеозаписи");
itemsObj.add("Контакты");
itemsObj.add("Мой профиль");
//get sidemenulistobject
ListView lv = ((ListView) ((Activity) context).findViewById(R.id.sidemenulistobject));
//add adapter
SlideAdapter adapter = new SlideAdapter((Activity) context, R.layout.sidemenu_item, itemsObj);
lv.setAdapter(adapter);
This is my SlideAdapter
public class SlideAdapter extends ArrayAdapter<MenuCategoryObject>{
ArrayList<String> listItems;
int Resourse;
Context context;
LayoutInflater vi;
private ImageLoader imageLoader;
public SlideAdapter(Context context, int resource, ArrayList<String> listItems) {
super(context, resource);
this.listItems = listItems;
Resourse = resource;
this.context = context;
vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null) {
convertView = vi.inflate(Resourse, null);
holder = new ViewHolder();
Typeface face=Typeface.createFromAsset(context.getAssets(), "font/AvenirNext-Medium.ttf");
holder.textSlide = (TextView) convertView.findViewById(R.id.textSlide);
holder.textSlide.setTypeface(face);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textSlide.setText(listItems.get(position));
return convertView;
}
static class ViewHolder {
public TextView textSlide;
}
}
But my item list view dont show. I dont know why. Please help
the problem is with your adapter. Since you are not providing the dataset to the super constructor, you have to override getCount and return its size. Add
public int getCount() {
return listItems.size();
}
to your adapter
I', trying to have simple PagerAdapter with horizontal scrolling in my Android application. I try to have a grid with images in the pages. What is the simplest way to achive that?
I try something like this(It doesn't work, :
It's my MainActivity.onCreate
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createHeroList();
LayoutInflater inflater = LayoutInflater.from(this);
List<View> pages = new ArrayList<View>();
View page = inflater.inflate(R.layout.page, null);
pages.add(page);
page = inflater.inflate(R.layout.page, null);
pages.add(page);
page = inflater.inflate(R.layout.page, null);
pages.add(page);
SamplePagerAdapter pagerAdapter = new SamplePagerAdapter(pages);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(pagerAdapter);
viewPager.setCurrentItem(1);
setContentView(viewPager);
initImageLoader(getApplicationContext());
}
It's my Image adapter
public class ImageAdapter extends BaseAdapter {
ImageLoader imageLoader = ImageLoader.getInstance();
private Context mContext;
ArrayList<String> HeroList;
String[] imageUrls;
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View grid;
DisplayImageOptions options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.ic_stub)
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error).cacheInMemory()
.cacheOnDisc().bitmapConfig(Bitmap.Config.RGB_565).build();
if (convertView == null) {
grid = new View(mContext);
// LayoutInflater inflater = getLayoutInflater();
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
grid = inflater.inflate(R.layout.cellgrid, parent, false);
} else {
grid = (View) convertView;
}
ImageView imageView = (ImageView) grid.findViewById(R.id.imagepart);
TextView textView = (TextView) grid.findViewById(R.id.textpart);
imageLoader.displayImage(imageUrls[position], imageView, options);
textView.setText(HeroList.get(position));
return grid;
}
}
and my PagerAdapter.
public class SamplePagerAdapter extends PagerAdapter{
List<View> pages = null;
ArrayAdapter<String> adapter;
ArrayList<String> NamesList = new ArrayList<String>();
int HeroCount = 98;
ImageLoader imageLoader = ImageLoader.getInstance();
String[] imageUrls;
public SamplePagerAdapter(List<View> pages){
this.pages = pages;
}
#Override
public Object instantiateItem(View collection, int position){
View v = pages.get(position);
GridView gridview = (GridView) v.findViewById(R.id.gridview);
Resources myResources = v.getResources();
imageUrls = myResources.getStringArray(R.array.Urls);
gridview.setAdapter(new ImageAdapter(v.getContext()));
gridview.setOnItemClickListener(gridviewOnItemClickListener);
((ViewPager) collection).addView(v, 0);
return v;
}
private GridView.OnItemClickListener gridviewOnItemClickListener = new GridView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
// TODO Auto-generated method stub
// Sending image id to FullScreenActivity
Intent i = new Intent(v.getContext(),
HeroInformation.class);
i.putExtra("HeroName", NamesList.get(position));
i.putExtra("HeroUrl", imageUrls[position]);
i.putExtra("HeroNum", position);
startActivity(i);
}
};
}