Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm trying use a StringArray to display items in a ListView with a custom Adapter.
But it does not work.
package ir.safarbazha.safarbazha.Acts;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.view.AbsSavedState;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.text.Format;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import javax.xml.datatype.DatatypeConstants;
import ir.safarbazha.safarbazha.Core.adapter.DrawerCustomListAdapter;
import ir.safarbazha.safarbazha.Core.app.AppController;
import ir.safarbazha.safarbazha.R;
import static ir.safarbazha.safarbazha.R.id.content_frame;
import static ir.safarbazha.safarbazha.R.id.toolbar;
public class HomeAct extends AppCompatActivity {
ActionBar homeActionbar;
String[] draweritems;
List<String> drawerItems;
int homeDrawerMenuItemsNumber=1;
DrawerCustomListAdapter drawerCustomListAdapter;
DrawerLayout homeDLayout;
ListView homeDrawerListView;
ImageView mainToolbarMenu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Localize...
if (!Locale.getDefault().getLanguage().equals("fa")){
String languageToLoad = "fa";
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
this.setContentView(R.layout.act_about);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
setContentView(R.layout.act_home);
homeDLayout=(DrawerLayout)findViewById(R.id.drawer_layout);
homeDrawerListView=(ListView)findViewById(R.id.drawer_lv);
//Set Custom ToolBar...
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
homeActionbar=getSupportActionBar();
final LayoutInflater inflator = (LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflator.inflate(R.layout.toolbar, null);
homeActionbar.setCustomView(v);
homeActionbar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
//Set Custom ToolBar Objects...
//MainToolBar Menu Image Object...
mainToolbarMenu=(ImageView)findViewById(R.id.nav_drawer_menu);
mainToolbarMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (homeDLayout.isDrawerOpen(GravityCompat.START))
homeDLayout.closeDrawer(GravityCompat.START);
else homeDLayout.openDrawer(GravityCompat.START);
}
});
//Set Custom Home Navigation Drawer...
draweritems= getResources().getStringArray(R.array.main_titles);
drawerItems=new ArrayList<String>(Arrays.asList(draweritems));
drawerCustomListAdapter=new DrawerCustomListAdapter(this,draweritems);
homeDrawerListView.setAdapter(drawerCustomListAdapter);
// homeDrawerListView.setAdapter(new ArrayAdapter<String>(
// this,R.layout.drawer_list_row,homeDrawerMenuItems));
// homeDrawerListView.setAdapter(new ArrayAdapter<String>(
// this,android.R.layout.simple_list_item_1,homeDrawerMenuItems));
homeDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selectedItem=getResources().getStringArray(R.array.main_titles)[position];
Toast.makeText(getBaseContext(),"برروی "+selectedItem+"کلیک شد!",Toast.LENGTH_SHORT).show();
}
});
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
}
package ir.safarbazha.safarbazha.Core.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import ir.safarbazha.safarbazha.R;
public class DrawerCustomListAdapter extends BaseAdapter{
public Context context;
public List<String> drawerItems;
private static LayoutInflater inflater=null;
public void drawerCustomListViewItemRow(
Context context,List<String> drawerItems
){
this.context=context;
this.drawerItems=drawerItems;
inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return drawerItems.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return drawerItems.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi = convertView;
if (vi == null)
vi = inflater.inflate(R.layout.drawer_list_row, null);
TextView title = (TextView) vi.findViewById(R.id.drawer_lv_title);
title.setText(drawerItems.get(position));
ImageView icon=(ImageView)vi.findViewById(R.id.drawer_lv_icon);
icon.setImageResource(R.drawable.ic_menu_left);
return vi;
}
/*
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.drawer_list_row, null);
TextView title = (TextView)vi.findViewById(R.id.drawer_lv_title); // title
ImageView icon=(ImageView)vi.findViewById(R.id.drawer_lv_icon); // thumb image
// Setting all values in listview
title.setText(R.string.app_name);
icon.setImageResource(R.drawable.ic_account_circle);
return vi;
}
*/
}
My Android Studio says that the problem is in HomeAct, where I typed: (this,draweritems);
You added void here, therefore creating a method, not a constructor. Constructors have no return type.
Remove it
public **void** drawerCustomListViewItemRow(
Context context,List<String> drawerItems
){
this.context=context;
this.drawerItems=drawerItems;
inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
Also capitalize the D for your class name from drawerCustomListViewItemRow to instead DrawerCustomListAdapter
And use the List of drawerItems, not the array draweritems when you create the adapter. Probably best to only store one or the other, not both anyway.
you have to add a constructor to your adapter class
change you'r drawerCustomListViewItemRow method name to this:
public DrawerCustomListAdapter(Context context, List<string> drawerItems)
and one more thing is that you have to either change String[] draweritems; in HomeAct to List<string> draweritems; or change the adapter List to string arary
I have modified your code. Please check the difference. Your DrawerCustomListAdapter constructor was not ok.
package ir.safarbazha.safarbazha.Acts;
import android.content.Context; import android.content.Intent; import
android.content.pm.ActivityInfo; import
android.content.res.Configuration; import android.os.Bundle; import
android.support.design.widget.FloatingActionButton; import
android.support.design.widget.Snackbar; import
android.support.v4.view.AbsSavedState; import
android.support.v4.view.GravityCompat; import
android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
import android.support.v4.widget.DrawerLayout; import
android.support.v7.app.ActionBar; import
android.support.v7.app.AlertDialog; import
android.support.v7.app.AppCompatActivity; import
android.support.v7.widget.Toolbar; import android.view.Gravity; import
android.view.LayoutInflater; import android.view.View; import
android.widget.AdapterView; import android.widget.ArrayAdapter; import
android.widget.ImageView; import android.widget.ListView; import
android.widget.Toast;
import java.lang.reflect.Field; import
java.lang.reflect.InvocationHandler; import java.text.Format; import
java.util.ArrayList; import java.util.Arrays; import
java.util.Comparator; import java.util.List; import java.util.Locale;
import javax.xml.datatype.DatatypeConstants;
import ir.safarbazha.safarbazha.Core.adapter.DrawerCustomListAdapter;
import ir.safarbazha.safarbazha.Core.app.AppController; import
ir.safarbazha.safarbazha.R;
import static ir.safarbazha.safarbazha.R.id.content_frame; import
static ir.safarbazha.safarbazha.R.id.toolbar;
public class HomeAct extends AppCompatActivity {
ActionBar homeActionbar;
String[] draweritems;
List<String> drawerItems;
int homeDrawerMenuItemsNumber = 1;
DrawerCustomListAdapter drawerCustomListAdapter;
DrawerLayout homeDLayout;
ListView homeDrawerListView;
ImageView mainToolbarMenu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Localize...
if (!Locale.getDefault().getLanguage().equals("fa")) {
String languageToLoad = "fa";
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
this.setContentView(R.layout.act_about);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
setContentView(R.layout.act_home);
homeDLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
homeDrawerListView = (ListView) findViewById(R.id.drawer_lv);
//Set Custom ToolBar...
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
homeActionbar = getSupportActionBar();
final LayoutInflater inflator = (LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflator.inflate(R.layout.toolbar, null);
homeActionbar.setCustomView(v);
homeActionbar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
//Set Custom ToolBar Objects...
//MainToolBar Menu Image Object...
mainToolbarMenu = (ImageView) findViewById(R.id.nav_drawer_menu);
mainToolbarMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (homeDLayout.isDrawerOpen(GravityCompat.START))
homeDLayout.closeDrawer(GravityCompat.START);
else homeDLayout.openDrawer(GravityCompat.START);
}
});
//Set Custom Home Navigation Drawer...
draweritems = getResources().getStringArray(R.array.main_titles);
drawerItems = new ArrayList<String>(Arrays.asList(draweritems));
drawerCustomListAdapter = new DrawerCustomListAdapter(this, draweritems);
homeDrawerListView.setAdapter(drawerCustomListAdapter);
// homeDrawerListView.setAdapter(new ArrayAdapter<String>(
// this,R.layout.drawer_list_row,homeDrawerMenuItems));
// homeDrawerListView.setAdapter(new ArrayAdapter<String>(
// this,android.R.layout.simple_list_item_1,homeDrawerMenuItems));
homeDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selectedItem = getResources().getStringArray(R.array.main_titles)[position];
Toast.makeText(getBaseContext(), "برروی " + selectedItem + "کلیک شد!", Toast.LENGTH_SHORT).show();
}
});
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
} }
package ir.safarbazha.safarbazha.Core.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import ir.safarbazha.safarbazha.R;
public class DrawerCustomListAdapter extends BaseAdapter {
public Context context;
public List<String> drawerItems;
private static LayoutInflater inflater = null;
public void DrawerCustomListAdapter(
Context context, List<String> drawerItems
) {
this.context = context;
this.drawerItems = drawerItems;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return drawerItems.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return drawerItems.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi = convertView;
if (vi == null)
vi = inflater.inflate(R.layout.drawer_list_row, null);
TextView title = (TextView) vi.findViewById(R.id.drawer_lv_title);
title.setText(drawerItems.get(position));
ImageView icon = (ImageView) vi.findViewById(R.id.drawer_lv_icon);
icon.setImageResource(R.drawable.ic_menu_left);
return vi;
}
/*
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.drawer_list_row, null);
TextView title = (TextView)vi.findViewById(R.id.drawer_lv_title); // title
ImageView icon=(ImageView)vi.findViewById(R.id.drawer_lv_icon); // thumb image
// Setting all values in listview
title.setText(R.string.app_name);
icon.setImageResource(R.drawable.ic_account_circle);
return vi;
}
*/ }
Related
I'm newbie and just study Java around 1 month.
i'm trying to create group picture by grid view and if i click any picture then show for user alert dialog ask user want to delete picture or not. But somehow when i try to set event for grid view by image. i can't start up app. can help me find where is crash cause app can't start up.
package com.example.hi.gridviewhinhanh;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<Danhsachhinhanh> manghinhanh;
HinhanhAdapter arrayAdapter;
GridView gridView;
ImageView imgView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView = findViewById(R.id.gridview);
manghinhanh = new ArrayList<>();
manghinhanh.add(new Danhsachhinhanh(R.drawable.chupanh));
manghinhanh.add(new Danhsachhinhanh(R.drawable.goidien));
manghinhanh.add(new Danhsachhinhanh(R.drawable.photoshop));
manghinhanh.add(new Danhsachhinhanh(R.drawable.quality));
manghinhanh.add(new Danhsachhinhanh(R.drawable.secutiry));
manghinhanh.add(new Danhsachhinhanh(R.drawable.signuptoday));
arrayAdapter = new HinhanhAdapter(MainActivity.this, manghinhanh);
gridView.setAdapter(arrayAdapter);
imgView = findViewById(R.id.imageviewHinhanh);
imgView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder hopthoai = new AlertDialog.Builder(MainActivity.this);
hopthoai.setTitle("Do you want to delete");
hopthoai.setMessage("Please confirm");
hopthoai.setIcon(R.mipmap.ic_launcher);
hopthoai.setCancelable(false);
hopthoai.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
hopthoai.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "You choose No", Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
package com.example.hi.gridviewhinhanh;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.List;
public class HinhanhAdapter extends BaseAdapter {
Context context;
ArrayList<Danhsachhinhanh> danhsachhinhanhArrayList;
public HinhanhAdapter (Context context, ArrayList<Danhsachhinhanh> danhsachhinhanhArrayList){
this.context = context;
this.danhsachhinhanhArrayList = danhsachhinhanhArrayList;
}
#Override
public int getCount() {
return danhsachhinhanhArrayList.size();
}
#Override
public Object getItem(int position) {
return danhsachhinhanhArrayList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.dong_item_gridviewhinhanh,null);
ImageView imageView = convertView.findViewById(R.id.imageviewHinhanh);
Danhsachhinhanh danhsachhinhanh = (Danhsachhinhanh) getItem(position);
imageView.setImageResource(danhsachhinhanh.getHinhanh());
return convertView;
}
}
place you imageView clickListener in Adapter's getView() and check it again.
Becuase your imageView does not exist there. For more information read about adapter and recycleview.
I am trying to create a grid view that loads images using an adapter.
I used Universal Image Loader for this purpose. When I run this, I get the error, "java.lang.IllegalStateException: Same jobid in systemuid."
I am unable to figure out as to what is the reason for this error. I am new to android development. Thanks in advance!
GridImageAdapter.java
package com.example.android.tabswithswipes.Utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import com.example.android.tabswithswipes.R;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import java.util.ArrayList;
/**
* Created by Chaitanya Shiva on 12-05-2018.
*/
public class GridImageAdapter extends ArrayAdapter<String>{
private Context mContext;
private LayoutInflater mInflater;
private int layoutResource;
private String mAppend;
private ArrayList<String> imgURLs;
public GridImageAdapter(Context context, int layoutResource, String append, ArrayList<String> imgURLs) {
super(context, layoutResource, imgURLs);
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mContext = context;
this.layoutResource = layoutResource;
mAppend = append;
this.imgURLs = imgURLs;
}
private static class ViewHolder{
ImageView image;
ProgressBar mProgressBar;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
/*
Viewholder build pattern (Similar to recyclerview)
*/
final ViewHolder holder;
if(convertView == null){
convertView = mInflater.inflate(layoutResource, parent, false);
holder = new ViewHolder();
holder.mProgressBar = (ProgressBar) convertView.findViewById(R.id.gridImageProgressBar);
holder.image = (ImageView) convertView.findViewById(R.id.gridImageView);
convertView.setTag(holder);
}
else{
holder = (ViewHolder) convertView.getTag();
}
String imgURL = getItem(position);
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(mAppend + imgURL, holder.image, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
if(holder.mProgressBar != null){
holder.mProgressBar.setVisibility(View.VISIBLE);
}
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
if(holder.mProgressBar != null){
holder.mProgressBar.setVisibility(View.GONE);
}
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if(holder.mProgressBar != null){
holder.mProgressBar.setVisibility(View.GONE);
}
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
if(holder.mProgressBar != null){
holder.mProgressBar.setVisibility(View.GONE);
}
}
});
return convertView;
}
}
The activity that uses gridView,
GalleryActivity.java
package com.example.android.tabswithswipes;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import com.example.android.tabswithswipes.Utils.GridImageAdapter;
import com.example.android.tabswithswipes.Utils.UniversalImageLoader;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.util.ArrayList;
/**
* Created by Chaitanya Shiva on 08-05-2018.
*/
public class GalleryFragment extends Activity {
private GridView gridView;
private ImageView galleryImage;
private ProgressBar mProgressBar;
private Spinner directorySpinner;
private Context mContext = GalleryFragment.this;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_gallery);
galleryImage = (ImageView)findViewById(R.id.galleryImageView);
gridView = (GridView)findViewById(R.id.gridView);
directorySpinner = (Spinner)findViewById(R.id.spinnerDirectory);
mProgressBar = (ProgressBar)findViewById(R.id.progressBar);
mProgressBar.setVisibility(View.GONE);
ImageView closeGallery = (ImageView)findViewById(R.id.closeGallery);
closeGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
TextView nextScreen = (TextView) findViewById(R.id.tvNext);
nextScreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
tempGridSetup();
}
private void setUpImageGrid(ArrayList<String> imgURLs){
GridView gridView = (GridView)findViewById(R.id.gridView);
GridImageAdapter adapter = new GridImageAdapter(mContext, R.layout.layout_grid_imageview,"", imgURLs);
gridView.setAdapter(adapter);
}
private void tempGridSetup(){
ArrayList<String> imgURLs = new ArrayList<>();
imgURLs.add("https://www.gstatic.com/webp/gallery/4.sm.jpg");
imgURLs.add("https://www.gstatic.com/webp/gallery3/1.sm.png");
imgURLs.add("https://cdn.pixabay.com/photo/2018/05/10/09/07/bleeding-heart-3387085_1280.jpg");
imgURLs.add("https://images.idgesg.net/images/article/2017/08/android_robot_logo_by_ornecolorada_cc0_via_pixabay1904852_wide-100732483-large.jpg");
imgURLs.add("https://www.androidcentral.com/sites/androidcentral.com/files/styles/xlarge_wm_brw/public/article_images/2018/03/android-p-logo-pixel-2-xl-5.jpg?itok=DB93lUGS");
imgURLs.add("https://www.androidcentral.com/sites/androidcentral.com/files/styles/xlarge_wm_brw/public/article_images/2018/03/android-p-virtual-notch.jpg?itok=EnKJzDgF");
imgURLs.add("https://www.androidcentral.com/sites/androidcentral.com/files/styles/xlarge_wm_brw/public/article_images/2018/03/samsung-galaxy-s9-plus-black-4.jpg?itok=bTitZlS_");
imgURLs.add("https://www.extremetech.com/wp-content/uploads/2017/03/smiling-android.jpg");
imgURLs.add("https://rimblogs.files.wordpress.com/2016/04/marshmallowman.png?w=800");
imgURLs.add("https://www.androidcentral.com/sites/androidcentral.com/files/topic_images/2015/android-apps-topic.png");
imgURLs.add("https://images.idgesg.net/images/article/2017/11/android-security-100741557-large.jpg");
setUpImageGrid(imgURLs);
}
}
I am having trouble loading images from internet into gridView. I am using Fresco for image loading. When I run the app, it doesn't crash but does not show the images in gridView. Also, there is no error shown in logcat. I am new to Android development. Thanks in advance!
GalleryFragment.java
package com.example.android.tabswithswipes;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import com.example.android.tabswithswipes.Utils.GridImageAdapter;
import com.example.android.tabswithswipes.Utils.UniversalImageLoader;
import com.facebook.drawee.view.SimpleDraweeView;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.util.ArrayList;
/**
* Created by Chaitanya Shiva on 08-05-2018.
*/
public class GalleryFragment extends Activity {
private GridView gridView;
private ImageView galleryImage;
private ProgressBar mProgressBar;
private Spinner directorySpinner;
private Context mContext = GalleryFragment.this;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_gallery);
galleryImage = (SimpleDraweeView)findViewById(R.id.galleryImageView);
gridView = (GridView)findViewById(R.id.gridView);
directorySpinner = (Spinner)findViewById(R.id.spinnerDirectory);
mProgressBar = (ProgressBar)findViewById(R.id.progressBar);
mProgressBar.setVisibility(View.GONE);
ImageView closeGallery = (ImageView)findViewById(R.id.closeGallery);
closeGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
TextView nextScreen = (TextView) findViewById(R.id.tvNext);
nextScreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
Uri uri = Uri.parse("https://www.gstatic.com/webp/gallery/4.sm.jpg");
galleryImage.setImageURI(uri);
tempGridSetup();
}
private void setUpImageGrid(ArrayList<String> imgURLs){
GridView gridView = (GridView)findViewById(R.id.gridView);
GridImageAdapter adapter = new GridImageAdapter(mContext, R.layout.layout_grid_imageview,"", imgURLs);
gridView.setAdapter(adapter);
}
private void tempGridSetup(){
ArrayList<String> imgURLs = new ArrayList<>();
imgURLs.add("https://www.gstatic.com/webp/gallery/4.sm.jpg");
imgURLs.add("https://www.gstatic.com/webp/gallery3/1.sm.png");
imgURLs.add("https://cdn.pixabay.com/photo/2018/05/10/09/07/bleeding-heart-3387085_1280.jpg");
imgURLs.add("https://images.idgesg.net/images/article/2017/08/android_robot_logo_by_ornecolorada_cc0_via_pixabay1904852_wide-100732483-large.jpg");
imgURLs.add("https://www.androidcentral.com/sites/androidcentral.com/files/styles/xlarge_wm_brw/public/article_images/2018/03/android-p-logo-pixel-2-xl-5.jpg?itok=DB93lUGS");
imgURLs.add("https://www.androidcentral.com/sites/androidcentral.com/files/styles/xlarge_wm_brw/public/article_images/2018/03/android-p-virtual-notch.jpg?itok=EnKJzDgF");
imgURLs.add("https://www.androidcentral.com/sites/androidcentral.com/files/styles/xlarge_wm_brw/public/article_images/2018/03/samsung-galaxy-s9-plus-black-4.jpg?itok=bTitZlS_");
imgURLs.add("https://www.extremetech.com/wp-content/uploads/2017/03/smiling-android.jpg");
imgURLs.add("https://rimblogs.files.wordpress.com/2016/04/marshmallowman.png?w=800");
imgURLs.add("https://www.androidcentral.com/sites/androidcentral.com/files/topic_images/2015/android-apps-topic.png");
imgURLs.add("https://images.idgesg.net/images/article/2017/11/android-security-100741557-large.jpg");
setUpImageGrid(imgURLs);
}
}
GridImageAdapter.java
package com.example.android.tabswithswipes.Utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import com.example.android.tabswithswipes.R;
import com.facebook.drawee.view.SimpleDraweeView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import java.util.ArrayList;
/**
* Created by Chaitanya Shiva on 12-05-2018.
*/
public class GridImageAdapter extends ArrayAdapter<String>{
private Context mContext;
private LayoutInflater mInflater;
private int layoutResource;
private String mAppend;
private ArrayList<String> imgURLs;
public GridImageAdapter(Context context, int layoutResource, String append, ArrayList<String> imgURLs) {
super(context, layoutResource, imgURLs);
this.mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.mContext = context;
this.layoutResource = layoutResource;
this.mAppend = append;
this.imgURLs = imgURLs;
}
private static class ViewHolder{
SimpleDraweeView image;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
/*
Viewholder build pattern (Similar to recyclerview)
*/
final ViewHolder holder;
if(convertView == null){
convertView = mInflater.inflate(layoutResource, parent, false);
holder = new ViewHolder();
holder.image = (SimpleDraweeView) convertView.findViewById(R.id.gridImageView);
convertView.setTag(holder);
}
else{
holder = (ViewHolder) convertView.getTag();
}
String imgURL = getItem(position);
holder.image.setImageURI(imgURL);
return convertView;
}
}
layout_grid_imageview.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<com.facebook.drawee.view.SimpleDraweeView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/gridImageView"
android:scaleType="centerCrop"/>
</RelativeLayout>
Here you forgot to hide the progressbar. You need to hide it when the image is loaded. You can do the following :
val controllerBuilder = Fresco.newDraweeControllerBuilder()
controllerBuilder.setUri(url)
controllerBuilder.oldController = drawee.controller
controllerBuilder.controllerListener = object : BaseControllerListener<ImageInfo>() {
override fun onFinalImageSet(id: String?, imageInfo: ImageInfo?, animatable: Animatable?) {
super.onFinalImageSet(id, imageInfo, animatable)
holder.mProgressBar.setVisibility(VISIBLE.GONE);
}
}
holder.image.controller = controllerBuilder.build()
I am trying to implement the custom list view in tabbed activity for youtube video playing app. I could not able to call custom listview adapter in fragment java class. I have tried to pass getActivity() to custom adapter but the app crashes. If any one know the solution please help me.
The java class are as follows:
HomeFragment.java
package layout;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
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.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
import in.testapp.app1.R;
public class HomeFragment extends Fragment {
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList();
private final List<String> mFragmentTitleList = new ArrayList();
public Adapter(FragmentManager manager) {
super(manager);
}
public Fragment getItem(int position) {
return (Fragment) this.mFragmentList.get(position);
}
public int getCount() {
return this.mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
this.mFragmentList.add(fragment);
this.mFragmentTitleList.add(title);
}
public CharSequence getPageTitle(int position) {
return (CharSequence) this.mFragmentTitleList.get(position);
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewpager);
setupViewPager(viewPager);
((TabLayout) view.findViewById(R.id.tablayout)).setupWithViewPager(viewPager);
return view;
}
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getChildFragmentManager());
adapter.addFragment(new YouTubeFragment(), "Tab 1");
adapter.addFragment(new SecondFragment(), "Tab 2");
viewPager.setAdapter(adapter);
}
}
YouTubeFragment.java
package layout;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import in.testapp.app1.AppUtils;
import in.testapp.app1.ChannelActivity;
import in.testapp.app1.CustomListAdapter;
import in.testapp.app1.R;
import in.testapp.app1.VideoDetails;
public class YouTubeFragment extends Fragment {
String TAG="MainActivity2";
ListView lvVideo;
ArrayList<VideoDetails> videoDetailsArrayList;
CustomListAdapter customListAdapter;
//{youtube_api_key} is replaced by actual key
String URL="https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UC5Eg6bkwsdCd-ZlcB3nt1dg&maxResults=25&key={youtube_api_key}";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_you_tube, container, false);
lvVideo=(ListView)view.findViewById(R.id.videoList);
videoDetailsArrayList=new ArrayList<>();
//App crashes here in the beolw line
customListAdapter=new CustomListAdapter(getActivity(),videoDetailsArrayList);
//App crashes here in the above line
showVideo();
return view;
}
private void showVideo() {
RequestQueue requestQueue= Volley.newRequestQueue(getContext());
StringRequest stringRequest=new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
JSONArray jsonArray=jsonObject.getJSONArray("items");
for(int i=1;i<jsonArray.length();i++){
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
JSONObject jsonVideoId=jsonObject1.getJSONObject("id");
JSONObject jsonsnippet= jsonObject1.getJSONObject("snippet");
JSONObject jsonObjectdefault = jsonsnippet.getJSONObject("thumbnails").getJSONObject("medium");
VideoDetails videoDetails=new VideoDetails();
String videoid=jsonVideoId.getString("videoId");
Log.e(TAG," New Video Id" +videoid);
videoDetails.setURL(jsonObjectdefault.getString("url"));
videoDetails.setVideoName(jsonsnippet.getString("title"));
videoDetails.setVideoDesc(jsonsnippet.getString("description"));
videoDetails.setVideoId(videoid);
videoDetailsArrayList.add(videoDetails);
}
lvVideo.setAdapter(customListAdapter);
customListAdapter.notifyDataSetChanged();
} 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);
}
}
CustomListAdapter.java
package in.testapp.app1;
import android.app.Activity;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import java.util.ArrayList;
public class CustomListAdapter extends BaseAdapter {
Activity activity;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
private LayoutInflater inflater;
ArrayList<VideoDetails> singletons;
public CustomListAdapter(Activity activity, ArrayList<VideoDetails> singletons) {
this.activity = activity;
this.singletons = singletons;
}
public int getCount() {
return this.singletons.size();
}
public Object getItem(int i) {
return this.singletons.get(i);
}
public long getItemId(int i) {
return (long) i;
}
public View getView(int i, View convertView, ViewGroup viewGroup) {
if (this.inflater == null) {
this.inflater = (LayoutInflater) this.activity.getLayoutInflater();
// getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = this.inflater.inflate(R.layout.videolist, null);
}
if (this.imageLoader == null) {
this.imageLoader = AppController.getInstance().getImageLoader();
}
NetworkImageView networkImageView = (NetworkImageView) convertView.findViewById(R.id.video_image);
final TextView imgtitle = (TextView) convertView.findViewById(R.id.video_title);
final TextView imgdesc = (TextView) convertView.findViewById(R.id.video_descriptio);
final TextView tvURL=(TextView)convertView.findViewById(R.id.tv_url);
final TextView tvVideoID=(TextView)convertView.findViewById(R.id.tv_videoId);
((LinearLayout) convertView.findViewById(R.id.asser)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(view.getContext(), VideoActivity.class);
intent.putExtra("videoId",tvVideoID.getText().toString());
view.getContext().startActivity(intent);
}
});
VideoDetails singleton = (VideoDetails) this.singletons.get(i);
networkImageView.setImageUrl(singleton.getURL(), this.imageLoader);
tvVideoID.setText(singleton.getVideoId());
imgtitle.setText(singleton.getVideoName());
imgdesc.setText(singleton.getVideoDesc());
return convertView;
}
}
VideoDeatils.java
package in.testapp.app1;
public class VideoDetails {
String VideoName;
String VideoDesc;
String URL;
String VideoId;
public void setVideoName(String VideoName){
this.VideoName=VideoName;
}
public String getVideoName(){
return VideoName;
}
public void setVideoDesc(String VideoDesc){
this.VideoDesc=VideoDesc;
}
public String getVideoDesc(){
return VideoDesc;
}
public void setURL(String URL){
this.URL=URL;
}
public String getURL(){
return URL;
}
public void setVideoId(String VideoId){
this.VideoId=VideoId;
}
public String getVideoId(){
return VideoId;
}
}
I used this tutorial to make a custom spinner but now I'm having a java.lang.OutOfMemoryError: Failed to allocate a 95976012 byte allocation with 16777120 free bytes and 31MB until OOMerror. I am aware that I should use bitmaps I just don't know how to include the bitmapFactory in my CustomAdapter. I have already compressed my images to sizes less than 16kb and put them in the mipmap folder because they are icons. I have also already tried
<application
android:largeHeap="true"
</application>
Here's my code :
MainActivity.java
package com.kathure.flags;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import static android.R.attr.id;
import static android.graphics.BitmapFactory.*;
import static java.security.AccessController.getContext;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
String[] countryNames= {
"Kenya" , "Malawi", "Nigeria", "Rwanda", "Tanzania", "Uganda"
};
int [] flags = {
R.mipmap.kenyamin,R.mipmap.malawimin, R.mipmap.nigeriamin, R.mipmap.rwandamin, R.mipmap.tanzaniamin, R.mipmap.ugandamin
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Getting the instance of Spinner and applying OnItemSelectedListener on it
Spinner spin = (Spinner) findViewById(R.id.simpleSpinner);
spin.setOnItemSelectedListener(this);
CustomAdapter customAdapter=new CustomAdapter(getApplicationContext(),flags,countryNames);
spin.setAdapter(customAdapter);
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(), countryNames[i], Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
CustomAdapter.java
package com.kathure.flags;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Created by kathure on 28/09/16.
*/
public class CustomAdapter extends BaseAdapter {
Context context;
int flags[];
String[] countryNames;
LayoutInflater inflter;
public CustomAdapter(Context applicationContext, int[] flags, String[] countryNames) {
this.context = applicationContext;
this.flags = flags;
this.countryNames = countryNames;
inflter = (LayoutInflater.from(applicationContext));
}
#Override
public int getCount() {
return flags.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.custom_spinner_items, null);
ImageView icon = (ImageView) view.findViewById(R.id.imageView);
TextView names = (TextView) view.findViewById(R.id.textView);
icon.setImageResource(flags[i]);
names.setText(countryNames[i]);
return view;
}
}