Displaying image retrieved from server - java

I am working on an Android app, in which the user uploads a photo. Now, I am calling a method from the server, which will return me a list of users. I would like to display this list along with the photos.
The images stored in the server are in byte-array. So I am converting them to String and then to Bitmap for showing. Unfortunately, it is not working as I am doing stuff with a Adapters as well. The image retrieved in adapter class is null. What am I doing wrong?
OtherUsers.java :
public class OtherUsers extends Activity {
private PersonServiceImpl personService = new PersonServiceImpl();
private static volatile List<RestPerson> restPersonList = new ArrayList<>();
public static final String firstName = "firstname";
public static final String userImage = "userimage";
static final Long userId = (long)0;
ListView listView;
UserAdapter userAdapter;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.displayuserlist);
restPersonList = this.personService.getOtherUsers();
// Base64 base64Encoder = new Base64();
ArrayList<HashMap<String, String>> usersArrayHashList = new ArrayList<>();
for(RestPerson restPerson : restPersonList){
HashMap<String, String> restDisplay = new HashMap<>();
restDisplay.put("userId",String.valueOf(restPerson.getUserId()));
restDisplay.put("firstName",restPerson.getFirstName());
restDisplay.put("userImage","data:image/png;base64," + Base64.encode(restPerson.getProfilePhoto()));
usersArrayHashList.add(restDisplay);
}
listView = (ListView) findViewById(R.id.usersdisplaylist);
userAdapter = new UserAdapter(this,usersArrayHashList);
listView.setAdapter(userAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Long userid = restPersonList.get(position).getUserId();
Log.d("Userid is ", String.valueOf(userid));
}
});
UserAdapter class :
public class UserAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public UserAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (convertView == null)
view = inflater.inflate(R.layout.userprofiles, null);
TextView username = (TextView) view.findViewById(R.id.userName);
ImageView userImage = (ImageView) view.findViewById(R.id.userImage);
HashMap<String, String> usersList = new HashMap<>();
usersList = data.get(position);
username.setText(usersList.get(OtherUsers.firstName));
String image = usersList.get(OtherUsers.userImage);
Log.d("Image is ",image);
byte[] newImageBytes = image.getBytes();
Bitmap bitmap = BitmapFactory.decodeByteArray(newImageBytes,0,newImageBytes.length);
userImage.setImageBitmap(bitmap);
userImage.setImageBitmap(null);
return view;
}
}
If there is any other information required, kindly let me know. Thanks.
Update
Sorry, forgot to put LogCat
08-24 13:43:16.618 29948-29948/internetlegion.com.gradlecheck E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: internetlegion.com.gradlecheck, PID: 29948
java.lang.NullPointerException: println needs a message
at android.util.Log.println_native(Native Method)
at android.util.Log.d(Log.java:139)
at internetlegion.com.gradlecheck.Adapters.UserAdapter.getView(UserAdapter.java:62)
at android.widget.AbsListView.obtainView(AbsListView.java:2347)
at android.widget.ListView.measureHeightOfChildren(ListView.java:1270)
at android.widget.ListView.onMeasure(ListView.java:1182)
at android.view.View.measure(View.java:17547)

data struct that you have used in adapter is very strange. it's better to create one class with three property and send one list of those to adapter class.
any way, your problem is :
public static final String userImage = "userimage";
you define userImage with value userimage, then you insert into hashmap with "userImage" that is not equal with value of userImage ( value have lower case i) then you have try to get "userimage" from hashmap that is not exists, so value is null.
Answer:
you can change following line:
restDisplay.put("userImage","data:image/png;base64," + Base64.encode(restPerson.getProfilePhoto()));
to
restDisplay.put(userImage,"data:image/png;base64," + Base64.encode(restPerson.getProfilePhoto()));
but better way is create custom object.

Related

how to create method in activity to put it in custom adapter listview?

at first I got an error " The code of method getView(int, View, ViewGroup) is exceeding the 65535 bytes limit " because I typed too much code, finally I created a method, but the method is error because the variable inside is not detected
I created Method _Differ();
public void _Differ() {
if (_position == 5) {
full.setText("iiii");
}
}
i put method Differ(); in custom adapter listview
this is my code in listview custom adapter
public class Listview1Adapter extends BaseAdapter {
ArrayList<HashMap<String, Object>> _data;
public Listview1Adapter(ArrayList<HashMap<String, Object>> _arr) {
_data = _arr;
}
#Override
public int getCount() {
return _data.size();
}
#Override
public HashMap<String, Object> getItem(int _index) {
return _data.get(_index);
}
#Override
public long getItemId(int _index) {
return _index;
}
#Override
public View getView(final int _position, View _v, ViewGroup _container) {
LayoutInflater _inflater = getLayoutInflater();
View _view = _v;
if (_view == null) {
_view = _inflater.inflate(R.layout.ccc, null);
}
final LinearLayout linear1 = _view.findViewById(R.id.linear1);
final LinearLayout linear2 = _view.findViewById(R.id.linear2);
final LinearLayout linear3 = _view.findViewById(R.id.linear3);
final LinearLayout linear4 = _view.findViewById(R.id.linear4);
final TextView textview1 = _view.findViewById(R.id.textview1);
final TextView full = _view.findViewById(R.id.full);
final TextView textview2 = _view.findViewById(R.id.textview2);
final TextView shortt = _view.findViewById(R.id.shortt);
final TextView name = _view.findViewById(R.id.name);
final TextView email = _view.findViewById(R.id.email);
full.setText(mapList.get((int)_position).get("end").toString());
shortt.setText(mapList.get((int)_position).get("rule").toString());
email.setText(mapList.get((int)_position).get("start").toString());
_Differ();
return _view;
}
}
//This is your method which will go in your activity >>
public void _Differ(TextView txt, int _position) {
if (_position == 5) {
txt.setText("iiii");
}
}
// This Code Goes in your ListAdpater >>
full.setText(mapList.get((int)_position).get("end").toString());
shortt.setText(mapList.get((int)_position).get("rule").toString());
email.setText(mapList.get((int)_position).get("start").toString());
_Differ(full, _position);
I think this can help you, By the way, Are you using Sketchware Pro đŸ¤”

Android : Add random data with different images and proper text

I am working on a demo android app. Currently, I have a list of products which I am displaying, but they all have same image and the text generated is also random characters generated with Java method. Needless to say, it doesn't look very good.
I am using an adapter and displaying the data. How can I efficiently use random images(either from URL or from a selected folder), and names from some XML file to make the UI look better.
Code :
public class Products extends Activity{
ProductAdapter productAdapter;
List<Product> productList = new ArrayList<>();
private SecureRandom random = new SecureRandom();
public static final String productName = "productName";
public static final String productComments = "productComments";
public static final String productLikes = "productLikes";
public static final String productDescription = "productDescription";
public static final String userName = "userName";
ListView productsList;
#Override
protected void onCreate(Bundle savedInstanceState) {
for(int i=1;i<100;i++){
Product product = createProduct();
productList.add(product);
}
ArrayList<HashMap<String, String>> productsArrayHashList = new ArrayList<>();
for (Product product : productList){
HashMap<String,String> productDisplay = new HashMap<>();
productDisplay.put(productName,product.getName());
productDisplay.put(productComments,String.valueOf(product.getCommentCount()));
productDisplay.put(productLikes,String.valueOf(product.getLikes()));
productDisplay.put(productDescription,product.getDescription());
productDisplay.put(userName,new BigInteger(130, random).toString(32));
productsArrayHashList.add(productDisplay);
}
productsList = (ListView) findViewById(R.id.productList);
productAdapter = new ProductAdapter(this,productsArrayHashList);
productsList.setAdapter(productAdapter);
}
public Product createProduct(){
int minimum = 1;
int maxValue = 20;
Product product = new Product();
product.setCommentCount(minimum + random.nextInt(maxValue - minimum + 1));
product.setLikes(minimum + random.nextInt(maxValue - minimum + 1));
product.setSaveDate(new Timestamp(System.currentTimeMillis()));
product.setDescription(new BigInteger(130, random).toString(32));
product.setName(new BigInteger(130, random).toString(32));
product.setSize(new BigInteger(130, random).toString(32));
if(getRandomBoolean()) {
product.setSold(true);
}else {
product.setSold(false);
}
return product;
}
Adapter code :
public class ProductAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
private SecureRandom random = new SecureRandom();
public ProductAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (convertView == null) {
view = inflater.inflate(R.layout.product_row, null);
TextView productName = (TextView) view.findViewById(R.id.productName);
TextView userUploader = (TextView)view.findViewById(R.id.uploadingUser);
RatingBar ratingBar = (RatingBar)view.findViewById(R.id.productStars);
TextView comments = (TextView) view.findViewById(R.id.comments);
TextView productDetails = (TextView) view.findViewById(R.id.description);
ImageView prodImage = (ImageView) view.findViewById(R.id.productImage);
prodImage.setImageResource(R.drawable.productwatch);
HashMap<String, String> productList;
productList = data.get(position);
productName.setText(productList.get(Products.productName));
comments.setText("Comments("+productList.get(Products.productComments)+")");
productDetails.setText(productList.get(Products.productDescription));
userUploader.setText(productList.get(Products.userName));
int minimum = 1;
int maxValue = 5;
ratingBar.setRating((float) (minimum + random.nextInt(maxValue - minimum + 1)));
}
return view;
}
}
Thank you.
I have a solution.
You'll need Picasso library for Android
Add this line to build.gradle under dependancies
compile 'com.squareup.picasso:picasso:2.5.2'
In your Adapter code, add this after initializing your ImageView.
Picasso.with(getApplicationContext)
.load("http://lorempixel.com/200/200/")
.into(imageView);`
For more info : Picasso - Github
The numbers after that URL are the dimensions, you can specify suitable dimensions.
I used http://lorempixel.com/ (Visit it to explore more features)
You can use any site to get the images.

String Values not showing in listview using base adapter

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));
}

Android : Setting and getting clicked item id for a list containing text and images.

I am working on an Android project in which I have a list of items shown to the user along-with its images. The problem right now is because of the modifications I had to do to set the list, I don't know how I can change the code to include the id of the object which is being clicked by the user. I would not like the position, but the id which is received from the server. Any help would be nice. Thanks a lot. :-)
Please note, relevant code is more in the first class below, I have just put the LazyAdapter if there are modifications requried in it. Thanks a lot.
GroupCanvasActivity.java :
public class GroupCanvasActivity extends Activity {
private static volatile Long groupAccountid = (long) 0;
List<RestCanvas> restCanvasList = new ArrayList<>();
private CanvasServiceImpl canvasService = new CanvasServiceImpl();
LazyAdapter lazyAdapter;
ListView listView;
static final String mcanvasid = "canvasid";
static final String mcanvastitle = "canvastitle";
static final String mcanvasname = "mcanvasname";
static final String mcanvasimage = "mcanvasimage";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.canvaslayout);
Bundle extras = getIntent().getExtras();
if (extras != null) {
groupAccountid = extras.getLong("groupid");
}
restCanvasList = this.canvasService.getGroupCanvasForGroupAccount(groupAccountid);
ArrayList<HashMap<String, String>> canvaslist = new ArrayList<HashMap<String, String>>();
for (RestCanvas restCanvas : restCanvasList) {
HashMap<String, String> canvasDisplay = new HashMap<>();
// The below mcanvasid is what I would like to get when clicked
canvasDisplay.put("mcanvasid", String.valueOf(restCanvas.getMcanvasid()));
canvasDisplay.put("mcanvastitle", restCanvas.getMcanvastitle());
canvasDisplay.put("mcanvasname", restCanvas.getMcanvasname());
canvasDisplay.put("mcanvasimage", restCanvas.getMcanvasimage());
canvaslist.add(canvasDisplay);
}
listView = (ListView) findViewById(R.id.canlist);
lazyAdapter = new LazyAdapter(this, canvaslist);
listView.setAdapter(lazyAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// In the for loop above, you can see the mcanvasid, which I would like to use here.
}
});
}
}
LazyAdapter.java :
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
}
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.activity_group_canvas, null);
TextView canvasName = (TextView)vi.findViewById(R.id.canvasname); // id
TextView canvasTitle = (TextView)vi.findViewById(R.id.canvastitle); // title
ImageView canvasImage=(ImageView)vi.findViewById(R.id.canvasimage); // image
HashMap<String, String> canvasList = new HashMap<String, String>();
canvasList = data.get(position);
canvasName.setText(canvasList.get(GroupCanvasActivity.mcanvasid));
canvasTitle.setText(canvasList.get(GroupCanvasActivity.mcanvasname));
canvasImage.setImageBitmap(convertByteArrayToBitmap(canvasList.get(GroupCanvasActivity.mcanvasimage)));
return vi;
}
private Bitmap convertByteArrayToBitmap(String string){
byte [] encodeByte= Base64.decode(string, Base64.DEFAULT);
return BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
}
}
Any help would be nice. Thank you. :-)
Do like this :
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String mcanvasid = restCanvasList.get(position).get("mcanvasid"); // Here you get the mcanvasid
}
});
try this. In your adapter:
public Object getItem(int position) {
return d.get(position);
}
, in your activity:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String output = (HashMap<String, String>)(parent.getAdapter.getItem(position)).get("mcanvasid");
//do what you want with output
}
});

Android BaseAdapter Dealing with an Empty ArrayList

I'm trying to populate a ListView with an ArrayList> using a base adapter. The ArrayList is populated by a database, and it is possible for the database to have no entries, and thus a empty ArrayList, for example when the app is launched for the first time. While the ArrayList is empty, I receive a non de-script "java.lang.RuntimeException: Unable to start activity ComponentInfo ... java.lang.NullPointerException".
My onCreate method looks like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.samples_list_layout);
mContext = getApplicationContext();
lv = getListView();
list = myDatabase.getInstance(mContext).getAllSamples();
sa = new SamplesAdapter(this, list);
lv.setAdapter(sa);
registerForContextMenu(lv);
}
Setting lv.setAdapter(null) will get the app to display the empty list view I have set up. However, when I leave it up to the BaseAdapter, I get the error.
I've followed the 2 Android List8.java and List14.java examples, and either way give the same results.
My BaseAdapter class looks like this:
public class SamplesAdapter extends BaseAdapter {
private static final String SAMPLE_NAME_COL = "name";
private static final String SAMPLE_HOST_COL = "host";
private static final String SAMPLE_ICON_COL = "icon";
private static final String SAMPLE_MODIFIED_STAMP_COL = "moddate";
private Context mContext;
private ArrayList<HashMap<String, String>> samples = new ArrayList<HashMap<String, String>>();
public SamplesAdapter(Context c, ArrayList<HashMap<String, String>> list){
mContext = c;
samples = list;
}
public int getCount() {
return samples.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.samples_row_layout, parent, false);
TextView name = (TextView) v.findViewById(R.id.samples_name);
name.setText(samples.get(position).get(SAMPLE_NAME_COL));
TextView host = (TextView) v.findViewById(R.id.samples_host);
host.setText(samples.get(position).get(SAMPLE_HOST_COL));
TextView moddate = (TextView) v.findViewById(R.id.samples_mod_stamp);
moddate.setText(samples.get(position).get(SAMPLE_MODIFIED_STAMP_COL));
return v;
}
}
I should also note that the ListView properly displays items when there is something to show. It only fails when the ArrayList is empty. Also, I'm using Android 2.2 (Not the greatest, I know). Any help would be greatly appreciated.
let getCount return 0, in orded to avoid the NPE:
public int getCount() {
return (samples == null) ? 0 : samples.size();
}

Categories

Resources