Display default contact photo in listView when no photo assigned? - Java for Android App Development

I have a listview which displays the Starred Contacts with photo and name. I've managed so far to display the photos of the contacts which have one. The problem is that when a contact hasn't a photo only the name displayed and not the default contact(from drawables).
Here is the related code:
Code:
Uri queryUri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.LOOKUP_KEY,
ContactsContract.Contacts.PHOTO_THUMBNAIL_URI,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.STARRED};
String selection =ContactsContract.Contacts.STARRED + "='1'";
Cursor cursor = managedQuery(queryUri, projection, selection,null,null);
long id= cursor.getColumnIndex(ContactsContract.Contacts._ID);
Bitmap bitmap = loadContactPhoto(getContentResolver(), id);
if(bitmap!=null){
favIcon.setImageBitmap(bitmap);
}
else{
}
String[] from = {ContactsContract.Contacts.PHOTO_THUMBNAIL_URI, ContactsContract.Contacts.DISPLAY_NAME};
int to[] = new int[]{
R.id.ivDefContact,
R.id.tvContactName
};
ListAdapter adapter = new SimpleCursorAdapter(
this,
R.layout.favs_list_item,
cursor,
from,
to,
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
final ListView listStarred = (ListView) findViewById(R.id.lvFavs);
listStarred.setAdapter(adapter);
}
public static Bitmap loadContactPhoto(ContentResolver cr, long id) {
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(cr, uri);
if (input == null) {
return null;
}
return BitmapFactory.decodeStream(input);
}
How can I achive this?
EDIT:
The app run fine, but I also get these errors on logcat:
I/System.out: resolveUri failed on bad bitmap uri:
E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /: open failed: EISDIR (Is a directory)
Click to expand...
Click to collapse

Did you managed to fix this? I have the same problem.

Related

Newbie url text download problem

Hi guys,
I am totally new at this. I mean completely raw .
I successfully put together a searchlight project by following a tutorial on youtube.
Now I want to do some work on a project that will fetch information from my employers website into the app. This information will be inform of text and images.
Here's the code I'm using in my attempt to read the remote text:
Code:
try {
URL url = new URL( "fullpath-url-to-file-dot-php" );
URLConnection conn = url.openConnection();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
while ((line = rd.readLine()) != null) {
Message lmsg;
lmsg = new Message();
lmsg.obj = line;
lmsg.what = 0;
Context context = getApplicationContext();
CharSequence text = "Hello toast! "+lmsg;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);toast.show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
Context context = getApplicationContext();
CharSequence text = "error!";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);toast.show();
}
I admit I barely know what I am doing. My attempt to download a simple line of text from a website url keeps failing.
Anyway, Can you guys give me an idea what I am doing wrong and what I should be doing instead?
Thanks
Update
I found out what the nature of the exception is.
It's a
Code:
java.net.socketexception: permission denied
exception.
Can anyone please shed some light on this for me ?
Did you add the internet permission to your manifest file?
Should be something like
<uses-permission>android.permission.INTERNET</uses-permission>

How to prevent laggy scrolling ListView w ImageView-Items filled with cached images?

Hello community,
I've got a ListActivity in my app, which shows Views including TextViews, for showing artist, title and album information of some mp3-Files (queried by my cursor), and an ImageView, for showing an albumart => Similar to the Tracklist in the music app.
Here's the code for my custom SimpleCursorAdapter and it's binding to the ListView:
Code:
void setListAdapterOverride() {
String[] fromColumns = new String[] {
AudioColumns.ARTIST,
MediaColumns.TITLE,
AudioColumns.ALBUM,
AudioColumns.ALBUM_ID
};
int[] toColumns = new int[] {
R.id.tv_artist,
R.id.tv_title,
R.id.tv_album,
R.id.iv_albumArt
};
cursorAdapter = new customAdapter(getBaseContext(), R.layout.listviewitem, cursor, fromColumns, toColumns);
setListAdapter(cursorAdapter);
if (MyDebug.Log)
Log.d("Activity", "ListAdapter gesetzt");
}
class customAdapter extends SimpleCursorAdapter {
int layout;
Cursor cursor;
String[] from;
int[] to;
public customAdapter(Context context, int layout, Cursor c,
String[] from, int[] to) {
super(context, layout, c, from, to);
this.layout = layout;
this.cursor = c;
this.from = from;
this.to = to;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = getLayoutInflater();
row = inflater.inflate(R.layout.listviewitem, parent, false);
if (MyDebug.Log)
Log.d("Activity", "Inflate");
}
cursor.moveToPosition(position);
TextView artist = (TextView) row.findViewById(to[0]);
TextView title = (TextView) row.findViewById(to[1]);
TextView album = (TextView) row.findViewById(to[2]);
ImageView albumArt = (ImageView) row.findViewById(to[3]);
artist.setText(cursor.getString(cursor.getColumnIndex(from[0])));
title.setText(cursor.getString(cursor.getColumnIndex(from[1])));
album.setText(cursor.getString(cursor.getColumnIndex(from[2])));
Cursor albumArtCursor = contentResolver.query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, new String[] { MediaStore.Audio.Albums._ID, MediaStore.Audio.Albums.ALBUM_ART }, MediaStore.Audio.Albums._ID + "='" + cursor.getInt(cursor.getColumnIndex(from[3])) + "'", null, null);
albumArtCursor.moveToFirst();
String albumArtUri = albumArtCursor.getString(albumArtCursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART));
if (albumArtUri == null) albumArtUri = "default";
if (!imageCache.containsKey(albumArtUri)) {
Bitmap albumArtBitmap;
if (!albumArtUri.equals("default")) {
Options opts = new Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(albumArtUri, opts);
Integer[] bitmapSize = new Integer[] { opts.outWidth, opts.outHeight };
Integer scaleFactor = 1;
while ((bitmapSize[0]/2 > 50) && (bitmapSize[1]/2 > 50)) {
scaleFactor++;
bitmapSize[0] /= 2;
bitmapSize[1] /= 2;
}
opts = new Options();
opts.inSampleSize = scaleFactor;
albumArtBitmap = BitmapFactory.decodeFile(albumArtUri, opts);
} else {
albumArtBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_mp_song_list);
}
imageCache.put(albumArtUri, albumArtBitmap);
}
albumArt.setImageBitmap(imageCache.get(albumArtUri));
return row;
}
}
imageCache is a Hashmap<String, Bitmap> for caching the Bitmaps, so they don't have to be decoded from file again when they had been cached before.
In a former version of the code, I didn't have the imageCache, so the albumarts were decoded from file everytime a new row has been added. That slowed down ListView-scrolling. By adding the imageCache scrolling in ListView doesn't lag that much as before, but it's lagging a bit sometimes.
Can anyone help me to further optimize my code to completely prevent lagging when I scroll the ListView?
Thanks regards ChemDroid

[Q] Parse Bluetooth received string

Hi, I have a newbie question..
I have modified the bluetoothChat example to get serial data from my pc to my phone over bluetooth.
The code uses the following code to keep listening for incoming data:
Code:
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[1024];
int bytes = 0;
// byte x = 0;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
// Start the service over to restart listening mode
BluetoothChatService.this.start();
break;
}
}
}
And in the MainActivity the following code when data is received:
Code:
case MESSAGE_READ:
byte [] readBuf;
//readBuf = (byte[]) msg.obj;
readBuf = (byte[]) msg.obj;
String readMessage = new String(readBuf, 0, msg.arg1); // create string from bytes array
messageString = messageString + readMessage;
if (messageString.length()<10){
TextView text = (TextView) findViewById(R.id.textView1); // Display output
text.setText("<10....");
break;
}
sb.append(readMessage); // append string
int endOfLineIndex = sb.indexOf("#"); // determine the end-of-line
if (endOfLineIndex > 0) { // if end-of-line,
String sbprint = sb.substring(0, endOfLineIndex); // extract string
sb.delete(0, sb.length()); // and clear
TextView text = (TextView) findViewById(R.id.textView1); // Display output
text.setText(sbprint);
mConversationArrayAdapter.add(mConnectedDeviceName+": " + readMessage);
}
break;
As shown i have added a endOfLineIndex loop to find the end of the received string and show the received string in a textfield. The problem with my code is when sending a string like "0123456789#" the shown text in the textView1 is mostly not the send string.. I get strings like 0123,4560123456789, etc.. Somehow there is still data in the buffer i quess.
Is there a way to clear or ignore the received data and only parse the wanted string form the buffer? If this is possible i can add a start identifier to the string..
The main goal is too parse a string like: #150,000,001,000,0.0,-0.1,40.3,144.0,001,OKE where each value is a variable which needed to be placed in a textview.
Thanks for any suggestions!
Kind regards,
Bas
This one "0123456789#" should return "0123456789". Does it?
You invoke substring().
Quote from the docs:
The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.
Click to expand...
Click to collapse
(http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#substring(int, int))
That means that the last character (the #) is missed out.
Thanks Nikwen,
I do miss out the end off string character #. The problem is i get different strings out of the buffer... If i send 0123456789# with a one second interval i get different results.. sometimes i get the string like expected which is 0123456789. but most of the time i get results like 0123, 456789,12,1,etc etc. it looks like the buffer is not cleared or something

ImageView from url in listview

i created a java web service. it returns ArrayList type(text,image URL).
and my client side code i receive the by following code:
public class CustomeAdapter extends ArrayAdapter<RowItem> {
private List<RowItem> objects;
Context context;
private Bitmap bitmap;
Drawable d;
ViewHolder holder = null;
public CustomeAdapter(Context context, int listViewResourceId, List<RowItem> first) {
super(context, listViewResourceId, first);
this.context = context;
}
private class ViewHolder {
ImageView image;
TextView name,service,local;
}
@suppressLint("NewApi")
public View getView(int position, View convertView, ViewGroup parent){
//ViewHolder holder = null;
RowItem rowItem = getItem(position);
//final Bitmap bitmap = null;
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.image=(ImageView) convertView.findViewById(R.id.imageView1);
holder.name = (TextView) convertView.findViewById(R.id.item_textView1);
holder.service = (TextView) convertView.findViewById(R.id.item_textView2);
holder.local = (TextView) convertView.findViewById(R.id.item_textView3);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.name.setText("Name:"+rowItem.getCustomerName());
holder.service.setText("Service:"+rowItem.getServiceName());
holder.local.setText("Locality:"+rowItem.getLocalityName());
String src="http://192.168.1.16:8080/"+rowItem.getImage();
try {
URL url = new URL(src);
bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
holder.image.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
return convertView;
}
i am getting followimg error:
android.os.NetworkOnMainThreadException
can any one help me
I think there is a library that does this well, but can't remember it right now...
Check the library repo, and some of the apps that list libraries. Also, maybe Google will turn up something helpful.
Lazy list perhaps?
https://github.com/thest1/LazyList

Java is too complex for begginer lovers

I love Android. I want to learn to develop apps. I keep reading tutorials. I got dissapointed and read about HTML frameworks (phonegap, etc). I came back to Android Native Java. I want to learn from the roots. However, some things discourages me....
All this part of the code is just for making a request to the Openweather API and get the json data (plus a little debugging stuff); which in Python or similar languages you only have to care about
- importing the library that handles http requests
- make the request in one function and save it into a json object
Code:
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
String format = "json";
String units = "metric";
int numDays = 7;
try {
final String FORECAST_BASE_URL =
"<the-domain>/data/2.5/forecast/daily?";
final String QUERY_PARAM = "q";
final String FORMAT_PARAM = "mode";
final String UNITS_PARAM = "units";
final String DAYS_PARAM = "cnt";
Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
.appendQueryParameter(QUERY_PARAM, params[0])
.appendQueryParameter(FORMAT_PARAM, format)
.appendQueryParameter(UNITS_PARAM, units)
.appendQueryParameter(DAYS_PARAM, Integer.toString(numDays))
.build();
URL url = new URL(builtUri.toString());
Log.v(LOG_TAG, "Built URI " + builtUri.toString());
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
forecastJsonStr = buffer.toString();
Log.v(LOG_TAG, "Forecast string: " + forecastJsonStr);
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
This is the complete Class:
Code:
public class FetchWeatherTask extends AsyncTask<String, Void, String[]> {
private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();
/* The date/time conversion code is going to be moved outside the asynctask later,
* so for convenience we're breaking it out into its own method now.
*/
private String getReadableDateString(long time){
// Because the API returns a unix timestamp (measured in seconds),
// it must be converted to milliseconds in order to be converted to valid date.
Date date = new Date(time * 1000);
SimpleDateFormat format = new SimpleDateFormat("E, MMM d");
return format.format(date).toString();
}
/**
* Prepare the weather high/lows for presentation.
*/
private String formatHighLows(double high, double low) {
// For presentation, assume the user doesn't care about tenths of a degree.
long roundedHigh = Math.round(high);
long roundedLow = Math.round(low);
String highLowStr = roundedHigh + "/" + roundedLow;
return highLowStr;
}
/**
* Take the String representing the complete forecast in JSON Format and
* pull out the data we need to construct the Strings needed for the wireframes.
*
* Fortunately parsing is easy: constructor takes the JSON string and converts it
* into an Object hierarchy for us.
*/
private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays)
throws JSONException {
// These are the names of the JSON objects that need to be extracted.
final String OWM_LIST = "list";
final String OWM_WEATHER = "weather";
final String OWM_TEMPERATURE = "temp";
final String OWM_MAX = "max";
final String OWM_MIN = "min";
final String OWM_DATETIME = "dt";
final String OWM_DESCRIPTION = "main";
JSONObject forecastJson = new JSONObject(forecastJsonStr);
JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);
String[] resultStrs = new String[numDays];
for(int i = 0; i < weatherArray.length(); i++) {
// For now, using the format "Day, description, hi/low"
String day;
String description;
String highAndLow;
// Get the JSON object representing the day
JSONObject dayForecast = weatherArray.getJSONObject(i);
// The date/time is returned as a long. We need to convert that
// into something human-readable, since most people won't read "1400356800" as
// "this saturday".
long dateTime = dayForecast.getLong(OWM_DATETIME);
day = getReadableDateString(dateTime);
// description is in a child array called "weather", which is 1 element long.
JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
description = weatherObject.getString(OWM_DESCRIPTION);
// Temperatures are in a child object called "temp". Try not to name variables
// "temp" when working with temperature. It confuses everybody.
JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
double high = temperatureObject.getDouble(OWM_MAX);
double low = temperatureObject.getDouble(OWM_MIN);
highAndLow = formatHighLows(high, low);
resultStrs[i] = day + " - " + description + " - " + highAndLow;
}
for (String s : resultStrs) {
Log.v(LOG_TAG, "Forecast entry: " + s);
}
return resultStrs;
}
@Override
protected String[] doInBackground(String... params) {
// If there's no zip code, there's nothing to look up. Verify size of params.
if (params.length == 0) {
return null;
}
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
String format = "json";
String units = "metric";
int numDays = 7;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page
final String FORECAST_BASE_URL =
"<the-domain>/data/2.5/forecast/daily?";
final String QUERY_PARAM = "q";
final String FORMAT_PARAM = "mode";
final String UNITS_PARAM = "units";
final String DAYS_PARAM = "cnt";
Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
.appendQueryParameter(QUERY_PARAM, params[0])
.appendQueryParameter(FORMAT_PARAM, format)
.appendQueryParameter(UNITS_PARAM, units)
.appendQueryParameter(DAYS_PARAM, Integer.toString(numDays))
.build();
URL url = new URL(builtUri.toString());
Log.v(LOG_TAG, "Built URI " + builtUri.toString());
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
forecastJsonStr = buffer.toString();
Log.v(LOG_TAG, "Forecast string: " + forecastJsonStr);
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
try {
return getWeatherDataFromJson(forecastJsonStr, numDays);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
// This will only happen if there was an error getting or parsing the forecast.
return null;
}
}
I mean, I know this code can be reduced, but I'm angry about the way it works. Everything needs to be passed to another object! And even rembember all those castings! Castings everywhere!
- The builded URI to the URL.
- The URL to the HttpConection variable.
- Once you connect, save that into the InputStream.
- Make a StringBuffer because we are going to send line by line everything.
- Then create the reader = new BufferedReader(new InputStreamReader(inputStream)).
- Append the lines to the buffer and return if it's ok.
- Else catch all the errors and be sure to close all the connections.
Damn Java !
Forgive me. You'll hate me.
Java is readable, that's the truth... but don't tell me that it is easy for a normal person.
Am I the only one?
If you are a beginner and will straight move to these classes. You will obviously find Java difficult. But Java is very easy if you move step by step from start
Sent from my XT1033 using XDA Premium 4 mobile app
---------- Post added at 04:18 PM ---------- Previous post was at 04:16 PM ----------
And that library also does the same thing inside. Only difference is, your work is already done by author of the library.
Sent from my XT1033 using XDA Premium 4 mobile app
Java is definitely a very verbose language but it's also widely used and so you will find many libraries that do tasks like grab JSON data from a service that have already been implemented for you
manwoman said:
Damn Java !
Forgive me. You'll hate me.
Java is readable, that's the truth... but don't tell me that it is easy for a normal person.
Am I the only one?
Click to expand...
Click to collapse
I don't think you're the only one. It's easy to get scared away by the many too verbose examples available, the key is to look at what you're trying to achieve and then break it up into those parts.
Your code listing is (I think) an attempt to show all steps to get the forecast data, but if that would have been broken up into smaller steps I don't think you'd look at it as quite as bad.
You would then have methods like
Code:
URL getForecastUrl(String parameter);
Code:
BufferedReader getUrl(URL url) { }
Code:
String readAll(BufferedReader reader) {}
Each of which would have had something like 6-7 lines of simple, cohesive code.
I understand your point, but in this particular scenario I think you're the victim of a poorly structured code sample rather than a too verbose language.
If you think the default implementation is too complicated, here are also many java libraries which will make your life easier.

Categories

Resources