android listview video thumbnail scrolling issue - android

I have listview with three viewholders one for image one for video one for audio
In videholder i have listview in which I am showing thumbnail of video if it downloaded.Its working fine but when i scroll then that thumbnail set on another imageview too.
mConvertView = convertView;
chatMessage=chatMessages.get(position);
final TextViewHolder mTextViewHolder;
final ImageViewHolder mImageViewHolder;
final AudioViewHolder mAudioViewHolder;
Object object=chatMessages.get(position);
// mHandler = new Handler();
disply = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisk(true)
.imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
.displayer(new RoundedBitmapDisplayer(20)).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
context).defaultDisplayImageOptions(disply).build();
ImageLoader.getInstance().init(config);
rd = new RecordBaseHandler(context);
if(chatMessage.getAssetsId() != null)
{
if(chatMessage.getType().equalsIgnoreCase("audio"))
{
Log.d("Node", "Item position is "+chatMessages.get(position));
mAudioViewHolder = getAudioViewHolder(mConvertView);
mAudioViewHolder.mChatmessage=chatMessage;
// TODO change below code
if(chatMessage.getSenderId() != null)
setAlignment(mAudioViewHolder, chatMessage.getSenderId().intValue() != ((SMBChatApp) context.getApplication()).getQbUser().getId().intValue());
else
setAlignment(mAudioViewHolder, false);
mAudioViewHolder.play.setTag(position);
mAudioViewHolder.txtInfo.setText(getTimeText(chatMessage.getDate_sent()));
mycontent = chatMessage.getProperty("content-type");
try {
Cursor rs = rd.getData(chatMessage.getAssetsId());
rs.moveToFirst();
filepath = rs.getString(rs.getColumnIndex("file_path"));
Log.d("Node", "FINALLY FILE PATH IS " + filepath);
if (!rs.isClosed()) {
rs.close();
}
if (filepath != null) {
mAudioViewHolder.download.setVisibility(View.GONE);
} else {
mAudioViewHolder.play.setVisibility(View.GONE);
mAudioViewHolder.download.setVisibility(View.VISIBLE);
}
} catch (Exception e) {
// TODO: handle exception
Log.d("Node", "EXECPTIOn " + e);
}
mAudioViewHolder.download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("Node: ", "Reading all contacts..");
List<RecordModel> contacts = rd.getAllContacts();
for (RecordModel cn : contacts) {
String log = "Id: "+ cn.getId()+ " ,Name: "+ cn.getAttch_id()+ " ,Phone: " + cn.getFile_path();
Log.d("Node: ",log);
}
// File tempMp3 = File.createTempFile("record", ".mp3", f);
new Thread()
{
public void run() {
File tempMp3 = null;
try {
tempMp3 = File.createTempFile("record", ".mp3",Environment.getExternalStorageDirectory());
} catch (IOException e) {
e.printStackTrace();
}
//We are creating folder first using mkdir
File f = new File(Environment.getExternalStorageDirectory()+ "/smbchat/");
if(!f.exists()){
f.mkdirs();
}
//then we want to store downloded file in that folder
File output = new File(f, "smb_" + System.currentTimeMillis() + "_audio.mp3");
Log.d("Node", "URL VALUE "+chatMessage.getUrl());
HttpRequest.get(chatMessage.getUrl()).receive(output);
audioFileName=String.valueOf(output);
Log.d("Node", "FILE SAVED SUCCESSFULLY"+tempMp3);
Log.d("Node", "FILE SAVED SUCCESSFULLY AUDIOFILENAME " + audioFileName);
context.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(context, "file downloaded successfully", Toast.LENGTH_LONG).show();
mAudioViewHolder.download.setVisibility(View.GONE);
}
});
rd.addContact(new RecordModel(chatMessage.getAssetsId(), audioFileName));
};
}.start();
}
});
mAudioViewHolder.play.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mAudioViewHolder.play.setVisibility(View.GONE);
mAudioViewHolder.pause.setVisibility(View.VISIBLE);
Log.d("DATA", "currently playing " + position);
playingAudioPosition = position;
Object tag = mAudioViewHolder.play.getTag();
// Here we get the position that we have set for the checkbox using setTag.
String str=chatMessage.getAssetsId();
Cursor rs = rd.getData(str);
rs.moveToFirst();
try
{
filepath = rs.getString(rs.getColumnIndex("file_path"));
}
catch(Exception e)
{
Toast.makeText(mConvertView.getContext(), "File is not downloaded", Toast.LENGTH_LONG).show();
}
Log.d("Node", "file path for id "+ str + "is "+ filepath);
if (!rs.isClosed()) {
rs.close();
}
if(filepath==null) //we check whether file is present or not
{
Toast.makeText(mConvertView.getContext(), "File is Not downloaded", Toast.LENGTH_SHORT).show();
((View)v.getParent()).findViewById(R.id.btndn).setVisibility(View.VISIBLE);
// mAudioViewHolder.download.setVisibility(mConvertView.VISIBLE);
}
else {
((View) v.getParent()).findViewById(
R.id.chat_audio_progress_bar)
.setVisibility(View.VISIBLE);
// mAudioViewHolder.progressBar.setVisibility(mConvertView.VISIBLE);
mediaPlayer = new MediaPlayer();
String yofile = "file://" + filepath;
mediaPlayer
.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(yofile);
} catch (IllegalArgumentException
| SecurityException
| IllegalStateException | IOException e) {
// TODO Auto-generated catch block
Log.e("Node", "ERRORSS Part 1 is" + e);
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp)
{
mAudioViewHolder.isPlaying = false;
/**
* since audio is stop
* playing, remove its
* position value
* */
playingAudioPosition = -1;
}
});
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Node", "ERRORSS is Part 2 " + e);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.start();
isMediaReleased = false;
mAudioViewHolder.progressBar.setMax(mediaPlayer.getDuration());
updateSeekBar();
}
}
});
mAudioViewHolder.pause
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAudioViewHolder.play.setVisibility(View.VISIBLE);
mAudioViewHolder.pause.setVisibility(View.GONE);
mediaPlayer.stop();
}
});
}
if (chatMessage.getType().equalsIgnoreCase("image") || chatMessage.getType().equalsIgnoreCase("photo"))
{
mImageViewHolder = getImageViewHolder(mConvertView);
mImageViewHolder.mChatmessage=chatMessage;
Log.d("Node", "this is Image position is "+chatMessages.get(position));
// TODO change below code
if(chatMessage.getSenderId() != null)
setAlignment(mImageViewHolder, chatMessage.getSenderId().intValue() != ((SMBChatApp) context.getApplication()).getQbUser().getId().intValue());
else
setAlignment(mImageViewHolder, false);
mImageViewHolder.txtInfo.setText(getTimeText(chatMessage.getDate_sent()));
if (chatMessage.getProperty("localfile") != null) {
imageUri1 = chatMessage.getProperty("localfile");
String status = chatMessage.getProperty("isUpload");
imageUri2 = "file://" + imageUri1;
Log.d("Node", "This time from local");
ImageLoader.getInstance().displayImage(chatMessage.getUrl(),
mImageViewHolder.myimageview, disply);
//
// Log.d("Node", "IMAGEURI is : " + imageUri2
// + "And status is " + status);
} else {
Log.d("Node", "Here we are now else");
ImageLoader.getInstance().displayImage(chatMessage.getUrl(),
mImageViewHolder.myimageview, disply);
}
mImageViewHolder.myimageview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "This is Image",
Toast.LENGTH_LONG).show();
Intent intent = new Intent(context,
ShowImgActivity.class);
String urll = chatMessage.getUrl();
Bitmap bitmap = mImageViewHolder.myimageview.getDrawingCache();
intent.putExtra("URL", urll);
intent.putExtra("BitmapImage", bitmap);
context.startActivity(intent);
}
});
}
//if aatchmnet is video then do this
else if (chatMessage.getType().equalsIgnoreCase("video")) {
mImageViewHolder = getImageViewHolder(mConvertView);
mImageViewHolder.mChatmessage=chatMessage;
// TODO change below code
if(chatMessage.getSenderId() != null)
setAlignment(mImageViewHolder, chatMessage.getSenderId().intValue() != ((SMBChatApp) context.getApplication()).getQbUser().getId().intValue());
else
setAlignment(mImageViewHolder, false);
mImageViewHolder.txtInfo.setText(getTimeText(chatMessage.getDate_sent()));
// Log.d("Node1", "This time from local videos");
if (chatMessage.getVideo_thumb() != null) {
Log.i("Node", "Yes this video has thumbnail");
Bitmap bitmp = StringToBitMap(chatMessage.getProperty("video_thumb"));
if (bitmp != null) {
mImageViewHolder.myimageview.setImageBitmap(bitmp);
} else {
mImageViewHolder.myimageview
.setImageResource(R.drawable.vids);
}
} else {
Log.i("Node", "Yes this dont have thumbanil");
ImageLoader.getInstance().displayImage(chatMessage.getUrl(),
mImageViewHolder.myimageview, disply);
}
mImageViewHolder.myimageview.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final ImageView imageThumbnail = (ImageView)v;
final Handler handler=new Handler() {
public void handleMessage(Message msg) {
Log.e("", "handeler bmVideoThumbnail"+bmVideoThumbnail);
if (bmVideoThumbnail!=null) {
imageThumbnail.setImageBitmap(bmVideoThumbnail);
}
};
};
new Thread()
{
public void run() {
//We are creating folder first using mkdir
File f = new File(Environment.getExternalStorageDirectory()+ "/smbchat/");
if(!f.exists()){
f.mkdirs();
}
//then we want to store downloded file in that folder
File output = new File(f, "VID_" + System.currentTimeMillis() + "_video.mp4");
Log.d("Node", "URL VALUE "+chatMessage.getUrl());
HttpRequest.get(chatMessage.getUrl()).receive(output);
audioFileName=String.valueOf(output);
Log.d("Node", "FILE SAVED SUCCESSFULLY AUDIOFILENAME " + audioFileName);
donloadedVideoUri= "file://" + audioFileName;
Log.e("Node", "donloadedVideoUri INSIDE THREAD------"+donloadedVideoUri);
bmVideoThumbnail=ThumbnailUtils.createVideoThumbnail(audioFileName, android.provider.MediaStore.Video.Thumbnails.MICRO_KIND);
Log.e("Node", "bmVideoThumbnail---------"+bmVideoThumbnail);
if(bmVideoThumbnail !=null)
handler.sendEmptyMessage(0);
};
}.start();
// String uriString = chatMessage.getUrl();
// Uri intentUri = Uri.parse(uriString);
//
// Intent intent2 = new Intent();
// intent2.setAction(Intent.ACTION_VIEW);
// intent2.setDataAndType(intentUri, "video/*");
// context.startActivity(intent2);
}
});
}
}
else {
mTextViewHolder = getTextViewHolder(mConvertView);
mTextViewHolder.mChatmessage=chatMessage;
Log.d("Node", "this is text position is "+chatMessages.get(position));
//TODO redo following logic
if(chatMessage.getSenderId() != null)
setAlignment(mTextViewHolder, chatMessage.getSenderId().intValue() != ((SMBChatApp) context.getApplication()).getQbUser().getId().intValue());
else
setAlignment(mTextViewHolder, false);
mTextViewHolder.txtInfo.setText(getTimeText(chatMessage.getDate_sent()));
mTextViewHolder.txtMessage.setText(chatMessage.getBody());
mTextViewHolder.message = chatMessage;
}
return mConvertView;

Use one ViewHolder and define three fields and show hide views according status.
Maintain Status in list not in adapter.
Because list item recreated on list view scroll.

You can see same thumbnail in multiple list items as Android reuses the view of list item.
Care needs to be taken that you make the thumbnail invisible or use 'Icon which suggests no image' if you don't have the correct image for that position of list item. This check has to be made in getView method of your adapter of the list.

Related

download picture from dropbox and watch it in one activity in android

I have 3 activities in my Android app. The first one opens an ssh connection and on my raspberry pi it does different kind of things (running python scripts, uploading stuff to dropbox etc). This process generally takes 15-20 seconds and when it is ready, the second activity comes up where i click a button that downloads the files, and then, on the third activity i can see the files that my rpi made.
I want to make the the last two activity into one, so the user does not have to click anything to download his or her file. Which is the easiest way? Can I solve this with delays or threads or only the asynctask remains?
The file gets downloaded earlier in the same activity as this placePic function and then I call it:
EDIT:
public class dropboxDownloader extends AppCompatActivity implements View.OnClickListener {
String apta;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pic_show);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
if (shouldAskPermissions()) {
askPermissions();
}
AndroidAuthSession session = null;
try {
session = buildSession();
} catch (DropboxException e) {
e.printStackTrace();
}
dropboxAPI = new DropboxAPI<>(session);
String[] fnames = null;
DropboxAPI.Entry dirent = null;
try {
dirent = dropboxAPI.metadata("/", 1000, null, true, null);
} catch (DropboxException e) {
e.printStackTrace();
}
ArrayList<DropboxAPI.Entry> files = new ArrayList<DropboxAPI.Entry>();
ArrayList<String> dir = new ArrayList<String>();
int i = 0;
for (DropboxAPI.Entry ent : dirent.contents) {
files.add(ent);// Add it to the list of thumbs we can choose from
//dir = new ArrayList<String>();
dir.add(files.get(i++).path);
}
apta = "something";
Dir.mkdirs();
final String DropboxDownloadPathTo = path + apta.substring(0, 30);
final String DropboxDownloadPathFrom = apta;
Toast.makeText(getApplicationContext(), "Download file ...", Toast.LENGTH_SHORT)
.show();
File file = new File(DropboxDownloadPathTo + DropboxDownloadPathFrom
.substring(DropboxDownloadPathFrom.lastIndexOf('.')));
if (file.exists()) file.delete();
try {
FileOutputStream outputStream = new FileOutputStream(file);
dropboxDownloader.dropboxAPI.getFile(DropboxDownloadPathFrom, null,
outputStream, null);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DropboxException e) {
Toast.makeText(this, "ez a hiba: " + e, Toast.LENGTH_SHORT).show();
}
placePic();
}
public void placePic() {
backToMenu = (Button) findViewById(R.id.button6);
backToMenu.setOnClickListener(this);
goToMyPics = (Button) findViewById(R.id.button5);
goToMyPics.setOnClickListener(this);
String this_pic = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/aha" + apta;
Toast.makeText(this, "this_pic: " + this_pic, Toast.LENGTH_LONG).show();
File f = new File(this_pic);
if (f.exists() && !f.isDirectory()) {
Toast.makeText(this, "delay begins", Toast.LENGTH_SHORT).show();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Toast.makeText(dropboxDownloader.this, "delayed?", Toast
.LENGTH_SHORT).show();
if (apta.startsWith("/pi_pic_lc")) {
String dedo = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/aha/" +
apta;
Toast.makeText(dropboxDownloader.this, "open this: " + dedo, Toast
.LENGTH_SHORT).show();
try {
ali.setImageURI(Uri.parse(dedo));
} catch (Exception e) {
Toast.makeText(dropboxDownloader.this, "error: " + e, Toast.LENGTH_SHORT)
.show();
}
} else {
String kutya = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/aha/"
+ apta;
Toast.makeText(dropboxDownloader.this, "open this: " + kutya, Toast
.LENGTH_SHORT).show();
try {
ali.setImageURI(Uri.parse(kutya));
PhotoViewAttacher pv = new PhotoViewAttacher(ali);
} catch (Exception e) {
Toast.makeText(dropboxDownloader.this, "error: " + e, Toast.LENGTH_SHORT)
.show();
}
}
}
}, 5000);
} else {
Toast.makeText(this, "cant get you the file", Toast.LENGTH_SHORT).show();
}
}
}
Thanks in advance!

How to clear User data and cache files for all installed applications programmatically in android

I'm doing an Android application which needs to list out all installed applications with cache size & app user data size. Now I want to clear the data (both cache & User data) of all installed applications. Below is my tried code.
Its not clearing data. When I go to Settings -> Applications -> Manage Applications -> Your Application -> Size is still showing as data & Cache. How could I remove those unused data for all installed applications. Thanks.
My code:
...
public static void trimCache(Context context) {
try {
File dir = context.getCacheDir();
if (dir != null && dir.isDirectory()) {
deleteDir(dir);
}
} catch (Exception e) {
// TODO: handle exception
}
}
public void clearApplicationData() {
File cache = getCacheDir();
File appDir = new File(cache.getParent());
if (appDir.exists()) {
String[] children = appDir.list();
for (String s : children) {
// if (!s.equals("lib")) {
deleteDir(new File(appDir, s));
Log.i("TAG", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
// }
}
}
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// The directory is now empty so delete it
return dir.delete();
}
private void showProgress(String message) {
pd = new ProgressDialog(this);
pd.setIcon(R.drawable.ic_launcher);
pd.setTitle("Please Wait...");
pd.setMessage(message);
pd.setCancelable(false);
pd.show();
}
long packageSize = 0, size = 0;
AppDetails cAppDetails;
public ArrayList<PackageInfoStruct> res;
private void getpackageSize() {
PACK_SIZE.clear();
DATA_SIZE.clear();
CACHE_SIZE.clear();
mPack = null;
mData = null;
mCache = null;
cAppDetails = new AppDetails(this);
res = cAppDetails.getPackages();
if (res == null)
return;
for (int m = 0; m < res.size(); m++) {
PackageManager pm = getPackageManager();
Method getPackageSizeInfo;
try {
getPackageSizeInfo = pm.getClass().getMethod(
"getPackageSizeInfo", String.class,
IPackageStatsObserver.class);
getPackageSizeInfo.invoke(pm, res.get(m).pname,
new cachePackState());
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
handle.sendEmptyMessage(ALL_PACAGE_SIZE_COMPLETED);
Log.v("Total Cache Size", " " + packageSize);
}
private Handler handle = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case FETCH_PACKAGE_SIZE_COMPLETED:
if (packageSize > 0)
size = (packageSize / 1024000);
lbl_cache_size.setText("Cache Size : " + size + " MB");
break;
case ALL_PACAGE_SIZE_COMPLETED:
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(
CacheList.this, mPack, mData, mCache);
lv.setAdapter(adapter);
if (null != pd)
if (pd.isShowing())
pd.dismiss();
break;
default:
break;
}
}
};
private class cachePackState extends IPackageStatsObserver.Stub {
#Override
public void onGetStatsCompleted(PackageStats pStats, boolean succeeded)
throws RemoteException {
Log.d("Package Size", pStats.packageName + "");
Log.i("Cache Size", pStats.cacheSize + "");
Log.w("Data Size", pStats.dataSize + "");
packageSize = packageSize + pStats.cacheSize;
Log.v("Total Cache Size", " " + packageSize);
PACK_SIZE.add(pStats.packageName);
DATA_SIZE.add(String.valueOf(pStats.dataSize / 1024000));
CACHE_SIZE.add(String.valueOf(pStats.cacheSize / 1024000));
mPack = PACK_SIZE.toArray(new String[PACK_SIZE.size()]);
mData = DATA_SIZE.toArray(new String[DATA_SIZE.size()]);
mCache = CACHE_SIZE.toArray(new String[CACHE_SIZE.size()]);
handle.sendEmptyMessage(FETCH_PACKAGE_SIZE_COMPLETED);
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_get_cacheSize:
size = 0;
packageSize = 0;
showProgress("Calculating Cache Size..!!!");
/**
* You can also use async task
* */
new Thread(new Runnable() {
#Override
public void run() {
getpackageSize();
}
}).start();
break;
case R.id.btn_clear_cache:
clearApplicationData();// Clear User Data
trimCache(CacheList.this);// Clear Cache Data
Toast.makeText(getApplicationContext(), "Successfully Cleared",
Toast.LENGTH_SHORT).show();
}
}

How can i update my custom listView display?

I'm working on a message application and wanna update my custom listView when new message arrive. I have tried several ways to do that but was unsuccessful ...please help with complete description cause m new to android. Here my code
public class SMSBroadcastReceiver extends BroadcastReceiver {
Messages message1;
MessageDbHelper db;
Context context=null;
SmsInboxList smsInboxList;
BroadcastReceiver br;
// ADapter adap;
private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
IntentFilter intentFilter=new IntentFilter(ACTION);
#SuppressLint("SimpleDateFormat")
#Override
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the intent.
Bundle bundle = intent.getExtras();
message1 = new Messages();
this.context=context;
// context = context.getApplicationContext();
smsInboxList = new SmsInboxList();
// adap=new ADapter(context, R.id.listView_Conversation);
MessageDbHelper dbMessagedbHelper = new MessageDbHelper(context, null,null, 0);
db = dbMessagedbHelper;
try {
if (bundle != null) {
Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
Long localLong = Long.valueOf(currentMessage.getTimestampMillis());
String datae = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(localLong.longValue()));
/*****************
** #here we getting data for notification
**
**/
try {
message1.body(message);
message1.number(senderNum);
message1.date(datae);
message1.type("1");
Log.i("" , "body++++++++++++++++" + message1.body);
Log.i("" , "num+++++++++++" + message1.number);
Log.i("" , "date+++++++++++" + message1.date);
Log.i("" , "typeeee++++++++++++" + message1.type);
db.insertDataInMsgTable(message1);
createNotification(context, message1);
} catch (Exception e) {
Log.i("", "except" + e);
}
Log.i("SmsReceiver", "senderNum: " + senderNum
+ "; message: " + message);
}
}
}
}
public void createNotification(Context context, Messages message1) {
Log.i("", "get body====" + message1.body + "---" + message1.number);
Intent intent = new Intent(context, SmsInboxList.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,intent, 0);
Notification notification = new NotificationCompat.Builder(context)
.setContentTitle("From: " + message1.number)
.setContentText(message1.body).setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.app_icon).build();
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notification.flags |= Notification.DEFAULT_LIGHTS;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
manager.notify(0, notification);
try
{
smsInboxList.adap.notifyDataSetChanged();
}
catch(Exception e)
{
Log.i("", "error in addd==="+e);
e.printStackTrace();
}
}
}
And main activity class is
public class SmsInboxList extends Activity {
public ListView listView;
public SmsInboxListAdapter adap ;
Contact con;
MessageDbHelper dbhelper;
ProgressBar prob;
LinearLayout rell;
public static TextView newMsg;
ImageView imgv;
ImageView imgv1;
ProgressBar pd;
Dialog dialog;
ArrayList<Messages> arrList = new ArrayList<Messages>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_sms_inbox_list);
pd = new ProgressBar(SmsInboxList.this);
pd = (ProgressBar) findViewById(R.id.progressBar_Inbox);
dbhelper = new MessageDbHelper(this, null, null, 0);
dbhelper.cleartable();
Log.i("", "qwertyu==" + dbhelper.getAllreceive().size());
listView = (ListView) findViewById(R.id.listView_Conversation);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
// TextView number=(TextView)findViewById(R.id.textViewName);
String addr = arrList.get(position).number; // number.getText().toString();
Log.i("" + position, "intent no==" + addr);
Intent intent = new Intent(getApplicationContext(),ConversationChat.class);
try {
String key_num = "numbrr";
intent.putExtra(key_num, addr);
Log.i("", "in intent put===" + addr);
} catch (Exception e) {
Log.i("", "putExtra==" + e);
}
startActivity(intent);
}
});
// prob=(ProgressBar)findViewById(R.id.progressBarInbox);
rell = (LinearLayout) findViewById(R.id.relativeLayout_sent);
imgv = (ImageView) findViewById(R.id.imageView_Setting);
imgv1 = (ImageView) findViewById(R.id.imageView_Compose);
newMsg = (TextView) findViewById(R.id.textView_Compose_new_message);
imgv1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),
SendMessage.class);
startActivity(intent);
}
});
newMsg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),
SendMessage.class);
startActivity(intent);
}
});
// ////////////////////////////////////
// /////////////////////////////////////////////////////////////////////////////////
imgv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Intent intent = new Intent(getApplicationContext(),FilterAct.class);
// startActivity(intent);
dialog=new Dialog(SmsInboxList.this);
dialog.setContentView(R.layout.activity_chat_theme);
dialog.setTitle("List");
ListView
listView=(ListView)dialog.findViewById(R.id.listView_chatTheme);
ArrayList<Messagesss> arr=new ArrayList<Messagesss>();
ArrayList<Messagesss> arr_sent=new ArrayList<Messagesss>();
final int
image_rec[]={R.drawable.recieve,R.drawable.receive_rec,R.drawable.rec_recei};
final int
image_sent[]={R.drawable.sentbubble,R.drawable.sent_rec,R.drawable.rec_sent};
for(int j=0;j<image_sent.length;j++)
{
Messagesss msg1=new Messagesss();
msg1.resid=image_sent[j];
arr_sent.add(msg1);
}
for(int i=0;i<image_rec.length;i++)
{
Messagesss msg=new Messagesss();
msg.resid=image_rec[i];
arr.add(msg);
}
final CategoryListAdapter1 adapter=new
CategoryListAdapter1(SmsInboxList.this,
R.id.listView_chatTheme,arr);
try{
listView.setAdapter(adapter);
}
catch(Exception e){
Log.i("", "error in adapter call"+e);
}
dialog.show();
listView.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
int val=adapter.getItem(position).resid;
Log.i("", ""+val);
Log.i("",
"adapter value======"+adapter.getItem(position).resid);
SharedPreferences mPrefs;
SharedPreferences.Editor editor;
mPrefs=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
editor = mPrefs.edit();
editor.putInt("hell_receive", image_rec[position]);
editor.putInt("hell_sent", image_sent[position]);
editor.commit();
dialog.dismiss();
}
});
}
});
// /////////////////////////////////////////////////////
// //////////////////////////////////////////////
// try {
// new ProgressTas().execute("");
// } catch (Exception e) {
// Log.i("", "error Progress Task==" + e);
// }
try{
getSMSInbox();
}
catch(Exception e)
{
Log.i("","getSMSInboxttry"+e);
}
ArrayList<Messages> mymsg = new ArrayList<Messages>(
dbhelper.getAllreceive());
dbhelper.insertDataInMsgTablePrimaryKey(mymsg);
dbhelper.getAllreceiveCommon();
for (int i = 0; i < mymsg.size(); i++) {
Log.i("" + i, "my dataaaa mymsg=====" + mymsg.get(i).number + "---"
+ mymsg.get(i).body + "---" + mymsg.get(i).type);
}
try{
addItem(listView);
}
catch(Exception e)
{
Log.i("", "error in call of addItem in smsInbox"+e);
}
/*
* Log.i("", "size my msg =="+mymsg.size()); ArrayList<Messages>
* testArr=new ArrayList<Messages>(dbhelper.getAllreceiveCommon());
*
* for(int i=0;i<testArr.size();i++) { Log.i(""+i,
* "my dataaaa mymsg test====="
* +testArr.get(i).number+"---"+testArr.get(i
* ).body+"---"+testArr.get(i).type);
*
* }
*/
// setup();
// updateUi(mymsg);
}
public void chatTheme(){
}
#SuppressWarnings({ "deprecation" })
public List<String> getSMSInbox() {
List<String> sms2 = new ArrayList<String>();
Uri uri = Uri.parse("content://sms");
Cursor c = getContentResolver().query(uri, null, null, null, null);
startManagingCursor(c);
arrList.clear();
// Read the msg data and store it in the list
if (c.moveToFirst()) {
for (int i = 0; i < c.getCount(); i++) {
Messages mssg = new Messages();
mssg.set_type("" + c.getString(c.getColumnIndexOrThrow("type")));
mssg.set_person(""
+ c.getString(c.getColumnIndexOrThrow("person")));
mssg.set_number(""
+ c.getString(c.getColumnIndexOrThrow("address")));
mssg.set_body("" + c.getString(c.getColumnIndexOrThrow("body")));
mssg.set_date(""
+ Functions.getTimefromMS(c.getString(c
.getColumnIndexOrThrow("date"))));
// Log.i(""+c.getString(c.getColumnIndexOrThrow("type")),
// "message==="+c.getString(c.getColumnIndexOrThrow("body")));
// Log.i(""+c.getString(c.getColumnIndexOrThrow("_id")),
// "reply path==="+c.getString(c.getColumnIndexOrThrow("reply_path_present")));
Log.i("SmsInboxList method part ",
"type===="+ c.getString(c.getColumnIndexOrThrow("type"))
+ "name===="+ c.getString(c.getColumnIndexOrThrow("person"))
+ "number=="+ c.getString(c.getColumnIndexOrThrow("address"))
+ "body===="+ c.getString(c.getColumnIndexOrThrow("body"))
+ "date===="+ c.getString(4));
dbhelper.insertDataInMsgTable(mssg);
c.moveToNext();
}
}
/*
* this is very important to dont close cursor if u dont wanna perform
* next activity and backtrack to previous activity
*/
// c.close();
// Set smsList in the arrList
adap = new SmsInboxListAdapter(getApplicationContext(), R.id.listView_Conversation);
dbhelper.insertDataInMsgTablePrimaryKey(dbhelper.getAllreceive());
arrList=new ArrayList<Messages>(dbhelper.getAllreceiveCommon());
Log.i("", "size cmn=="+arrList.size());
// listView.removeAllViews();
try {
try{
adap.notifyDataSetChanged();
}
catch(Exception e)
{
Log.i("", "error in notify dataset"+e);
}
listView.setAdapter(adap);
}
catch (Exception e) {
Log.i("", "listView" + e);
}
for (int i = 0; i < arrList.size(); i++)
{
adap.add(arrList.get(i));
Log.i("", "oyee!!!");
try{
adap.notifyDataSetChanged();
}
catch(Exception e)
{
Log.i("", "error in notify in smsInboxList=="+e);
}
}
Button button=(Button)findViewById(R.id.btn_notify);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{
getSMSInbox();
Log.i("", "getSmsInbox size of array list=="+arrList.size());
}catch(Exception e)
{
Log.i("", "error in notify click");
e.printStackTrace();
}
}
});
return sms2;
//
}
}
Use
listView.invalidate();
after you have made changes to the list
Eg. you have added/removed/updated data in listView.
Just an idea:
Call your code public CategoryListAdapter1 adapter; as global to class.
Use adapter.notifyDataSetChanged(); whenever your list going to refresh.

Notify when download finish dropbox Core API

I'm making a module that can download all file from apps folder on dropbox to devices.
Now, I'm using Core API to download a file. Everything works fine. But with multiple file, I don't know when the current file finish download to go to the next file.
Here is my download code:
final String cachePath = FileHandler.ROOT_LOCAL_FOLDER_DIR + "/" + mFile.getFileName();
try {
mFos = new FileOutputStream(cachePath);
} catch (FileNotFoundException e) {
mErrorMsg = "Couldn't create a local file to store the image";
return false;
}
ProgressListener mProgressLisenter = new ProgressListener() {
#Override
public void onProgress(long arg0, long arg1) {
// TODO Auto-generated method stub
tmpFile = new File(cachePath);
OnDownloadProgressDropboxChecked(FileHandler.PROGRESS_STATUS_ONPROGRESS, (int) (arg0 * 100 / arg1));
}
#Override
public long progressInterval() {
return 100;
}
};
mDownloaded = mApi.getFile(mFile.getFileId(), null, mFos, mProgressLisenter);
OnDownloadDropboxChecked(TRUE, "Download complete");
} catch (DropboxUnlinkedException e) {
mErrorMsg = "Unlinked";
} catch (DropboxPartialFileException e) {
// We canceled the operation
mErrorMsg = "Download canceled";
} catch (DropboxServerException e) {
}
}
I've tried:
Catch progress download, when reached 100% then notify - On this way, the OnProgress of dropbox isn't show up imediately and sometime It not reach 100%
Put It in a asynctask - Useless
I'm out of idea now, any advance are good for me.
Edited:
the solution is put some trigger under getFile() then It work.
here is my complete class:
public class DownloadFile extends AsyncTask<Void, Long, Boolean> implements DConst {
Context act;
private DropboxAPI<?> mApi;
// private String mPath;
private FileOutputStream mFos;
private boolean mCanceled;
private Long mFileLen;
private String mErrorMsg;
private String mFileName;
String path;
DFile mFile;
DropboxAPI.DropboxFileInfo mDownloaded;
#SuppressWarnings("deprecation")
public DownloadFile(Context act, DropboxAPI<?> api, DFile mDFile) {
// We set the context this way so we don't accidentally leak activities
this.act = act;
mApi = api;
mFile = mDFile;
path = mDFile.getFileId();
mFileName = mDFile.getFileName();
OnDownloadProgressDropboxChecked(FileHandler.PROGRESS_STATUS_START, 0);
}
File tmpFile;
#Override
protected Boolean doInBackground(Void... params) {
try {
final String cachePath = FileHandler.ROOT_LOCAL_FOLDER_DIR + "/" + mFile.getFileName();
try {
mFos = new FileOutputStream(cachePath);
} catch (FileNotFoundException e) {
mErrorMsg = "Couldn't create a local file to store the image";
return false;
}
ProgressListener mProgressLisenter = new ProgressListener() {
#Override
public void onProgress(long arg0, long arg1) {
// TODO Auto-generated method stub
tmpFile = new File(cachePath);
OnDownloadProgressDropboxChecked(FileHandler.PROGRESS_STATUS_ONPROGRESS, (int) (arg0 * 100 / arg1));
Log.d("Dolphin got interval", String.valueOf(tmpFile.length() + " - " + arg0 + " - " + arg1));
}
#Override
public long progressInterval() {
return 100;
}
};
mDownloaded = mApi.getFile(mFile.getFileId(), null, mFos, mProgressLisenter);
} catch (DropboxUnlinkedException e) {
mErrorMsg = "Unlinked";
} catch (DropboxPartialFileException e) {
// We canceled the operation
mErrorMsg = "Download canceled";
} catch (DropboxServerException e) {
// Server-side exception. These are examples of what could happen,
// but we don't do anything special with them here.
if (e.error == DropboxServerException._304_NOT_MODIFIED) {
// won't happen since we don't pass in revision with metadata
} else if (e.error == DropboxServerException._401_UNAUTHORIZED) {
// Unauthorized, so we should unlink them. You may want to
// automatically log the user out in this case.
} else if (e.error == DropboxServerException._403_FORBIDDEN) {
// Not allowed to access this
} else if (e.error == DropboxServerException._404_NOT_FOUND) {
// path not found (or if it was the thumbnail, can't be
// thumbnailed)
} else if (e.error == DropboxServerException._406_NOT_ACCEPTABLE) {
// too many entries to return
} else if (e.error == DropboxServerException._415_UNSUPPORTED_MEDIA) {
// can't be thumbnailed
} else if (e.error == DropboxServerException._507_INSUFFICIENT_STORAGE) {
// user is over quota
} else {
// Something else
}
// This gets the Dropbox error, translated into the user's language
mErrorMsg = e.body.userError;
if (mErrorMsg == null) {
mErrorMsg = e.body.error;
}
} catch (DropboxIOException e) {
// Happens all the time, probably want to retry automatically.
mErrorMsg = "Network error. Try again.";
} catch (DropboxParseException e) {
// Probably due to Dropbox server restarting, should retry
mErrorMsg = "Dropbox error. Try again.";
} catch (DropboxException e) {
// Unknown error
mErrorMsg = "Unknown error. Try again.";
} finally {
if (mFos != null) {
try {
mFos.close();
return true;
} catch (IOException e) {
}
}
}
return false;
}
#Override
protected void onPostExecute(Boolean result) {
OnDownloadProgressDropboxChecked(FileHandler.PROGRESS_STATUS_FINISH, 0);
if (result) {
OnDownloadDropboxChecked(TRUE, "Download complete");
} else {
OnDownloadDropboxChecked(FALSE, mErrorMsg);
}
}
OnAsyncDownloadListener onAsyncDownloadListener;
OnAsyncDownloadProgressListener onAsyncDownloadProgressListener;
private void OnDownloadDropboxChecked(int res, String messenger) {
if (onAsyncDownloadListener != null) {
onAsyncDownloadListener.OnAsyncDownload(res, messenger);
}
}
private void OnDownloadProgressDropboxChecked(int status, int percent) {
if (onAsyncDownloadProgressListener != null) {
onAsyncDownloadProgressListener.OnAsyncDownloadProgress(status, percent);
}
}
public void setOnAsyncDownloadListener(OnAsyncDownloadListener listener) {
onAsyncDownloadListener = listener;
}
public void setOnAsyncDownloadProgressListener(OnAsyncDownloadProgressListener listener) {
onAsyncDownloadProgressListener = listener;
}
public interface OnAsyncDownloadListener {
public abstract void OnAsyncDownload(int res, String messenger);
}
public interface OnAsyncDownloadProgressListener {
public abstract void OnAsyncDownloadProgress(int status, int percent);
}
}
The error caused by 'OnDownloadDropboxChecked()' of Asynctask fired before the one of getFile(). So It return a false notify.
Converting my comment to an answer:
If I'm reading this right, you're using the Android Core API SDK, right? If so, I think that when mApi.getFile returns, the file has been downloaded. So you can do whatever you need to do on the next line.

Updating the profile picture of a user

I am making an application where I am using ImageLoading Framework for downloading the images from the server and put the URLs in the cache. Now I want the user's profile picture updating but even after updation of the profile pic on the sever it's not displaying in the application.
The app is showing the old profile pic of the User. Why this problem is arising and how can I troubleshoot?
Code for update onclick:
update_profile_pic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP);
String value_for_test="delete";
Toast.makeText(getBaseContext(), "it works", Toast.LENGTH_SHORT).show();
Intent i=new Intent(getApplicationContext(),ProfilePictureCaptureHomeActivity.class);
i.putExtra("image",value_for_test);
startActivity(i);
Profile Pic CaptureHome
DBAdapter db = new DBAdapter(getApplicationContext());
db.open();
if (null == phoneNumber)
{
Cursor c = db.getUserInfo();
phoneNumber = c.getString(0);
imageUrl = c.getString(1);
System.out.println("the imageUrl is"+imageUrl);
c.close();
}
setContentView(R.layout.profilepic_capture);
if (null == imageUrl)
{
Cursor imageUrlObj = db.getUserInfo();
imageUrl = imageUrlObj.getString(1);
System.out.println("the imageurl is"+imageUrl);
imageUrlObj.close();
}
db.close();
for updating the profile picture:
if(image!=null){
Toast.makeText(getApplicationContext(), "Redirected", Toast.LENGTH_LONG).show();
imageUrl=null;
}
if(imageUrl != null)
{
Intent uploadimg = new Intent(ProfilePictureCaptureHomeActivity.this,ListeningAndSharingHomeActivity.class);
uploadimg.putExtra("phoneNumber", phoneNumber);
startActivity(uploadimg);
}
else
{
Log.v("ProfilePictureCaptureHomeActivity", "Staying Here");
}
_gallerybutton = (ImageButton) findViewById(R.id.btn_gallery);
_photobutton = (ImageButton) findViewById(R.id.btn_photo);
System.out.println("here in popup phoneeeeee" + phoneNumber);
System.out.println("here in flag************" + firstUpload);
_gallerybutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
v.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP);
System.out.println("here in galleryyyyyyyyyy");
Intent uploadimg = new Intent(ProfilePictureCaptureHomeActivity.this,ProfilePicFromGallery.class);
uploadimg.putExtra("phoneNumber", phoneNumber);
startActivity(uploadimg);
}
});
_photobutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
v.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP);
System.out.println("here in take piccccc");
Intent capIntent = new Intent(ProfilePictureCaptureHomeActivity.this,ProfilePicFromCamera.class);
startActivity(capIntent);
}
});
have a look at this code.
private String deleteExistingFile(String url , Context context)
{
String SaveFolderName = context.getFilesDir().getAbsolutePath() + "/yourinternalmemoryfolder";
String str_randomnumber= url.substring(url.lastIndexOf("/") + 1);
File wallpaperDirectory = new File(SaveFolderName);
if (!wallpaperDirectory.exists())
wallpaperDirectory.mkdirs();
String Photo_ImagePath=SaveFolderName+"/" + str_randomnumber ;
String result = "";
System.out.println("file path to be deleted " + Photo_ImagePath);
File f = new File(Photo_ImagePath);
if (f.exists())
{
System.out.println(" EEEEEEEEEEXXXXXXXXIIIIISSSSSSSTTTTTTT ");
try {
if(f.delete() == true){
result = "Success";
}else{
result = "Failure";
}
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "Error";
}
}
System.out.println("deleting existing file " + result);
return result;
}

Categories

Resources