Related
I want to show Toast (or progress bar) when clicking on the button "btnSearchImg". If before upload image, button clicked say "first pick image from gallary" and if after upload image clicked say "waiting". the toast before uploading image work fine but after uploading didn't work fine! my entire Activity code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_by_image);
Toasty.Config.getInstance().setTextSize(15).apply();
mSharedPreferences = getSharedPreferences("PREFERENCE", Context.MODE_PRIVATE);
mEditor = mSharedPreferences.edit();
mEditor.putString(PREF_SKIP,null);
if(mSharedPreferences.contains(PREF_SKIP)){
Log.i("payment", "true");
} else {
try {
}catch (Exception e){
Toast.makeText(getApplicationContext(), "ERORR", Toast.LENGTH_LONG).show();
}
}
context = getApplicationContext();
pbImgRetrvialProccess = (ProgressBar)findViewById(R.id.pbImgRetrvialProccess);
tvPermissionLoadImg = (TextView)findViewById(R.id.tvPermissionLoadImg);
tvPermissionLoadImg.setTypeface(Base.getIranSansFont());
TextView tvSearchImageToolBarText = (TextView) findViewById(R.id.tvSearchImageToolBarText);
tvSearchImageToolBarText.setTypeface(Base.getIranSansFont());
ivGalleryImgLoad = (ImageView) findViewById(R.id.ivGalleryImgLoad);
btnSearchImgLoad = (Button) findViewById(R.id.btnSearchImgLoad);
btnSearchImg = (Button) findViewById(R.id.btnSearchImg);
btnSearchImgLoad.setOnClickListener(this);
btnSearchImg.setOnClickListener(this);
}
public StringBuilder uniformQuantization( File filePath ){...}
private StringBuilder chHistogram( Mat newImage ){...}
private void CopyAssets(String filename){...}
private void copyFile(InputStream in, OutputStream out) throws IOException {...}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSearchImgLoad:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PICK_IMAGE);}
OpenGallery();
break;
case R.id.btnSearchImg:
Toasty.success(getBaseContext(), "Waiting...", Toast.LENGTH_LONG).show();
FindSimilarRequestedImage();
break;
}
}
private void OpenGallery() {
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery, PICK_IMAGE);
}
private void FindSimilarRequestedImage() {
if (ivGalleryImgLoad.getDrawable() != null) {
File loadedImageFilePath = new File(getRealPathFromURI(selectedImageUri));
queryFeatureX = uniformQuantization(loadedImageFilePath);
dateiLesenStringBuilder();
} else {
Toasty.error(getBaseContext(), "first pick image from gallary", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE && data != null) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PICK_IMAGE);
} else {
selectedImageUri = data.getData();
ivGalleryImgLoad.setImageURI(selectedImageUri);
tvPermissionLoadImg.setVisibility(View.INVISIBLE);
}
}
}
private String getRealPathFromURI(Uri contentURI) {
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
private void dateiLesenStringBuilder() {
FEATURE_PATH = context.getCacheDir().getPath() + "/" + FEATURE_NAME;
try {
FileOutputStream out = new FileOutputStream(FEATURE_PATH);
InputStream in = context.getAssets().open("coins/"+FEATURE_NAME);
byte[] buffer = new byte[1024];
int ch;
while ((ch = in.read(buffer)) > 0){
out.write(buffer, 0, ch);
}
out.flush();
out.close();
in.close();
}catch (Exception e){
System.out.println(e);
}
final File featureList = new File(FEATURE_PATH);
Runnable runner = new Runnable() {
BufferedReader in = null;
#Override
public void run() {
try {
String sCurrentLine;
int lines = 0;
BufferedReader newbw = new BufferedReader(new FileReader(featureList.getAbsolutePath()));
while (newbw.readLine() != null)
lines++;
in = new BufferedReader(new FileReader(featureList.getAbsolutePath()));
ArrayList<Double> nDistVal = new ArrayList<Double>();
ArrayList<String> nImagePath = new ArrayList<String>();
int count = 0;
while ((sCurrentLine = in.readLine()) != null) {
String[] featX = sCurrentLine.split(";")[1].split(" ");
nImagePath.add(sCurrentLine.split(";")[0]);
nDistVal.add(Distance.distL2(featX, queryFeatureX.toString().split(" ")));
count++;
}
ArrayList<Double> nstore = new ArrayList<Double>(nDistVal); // may need to be new ArrayList(nfit)
double maxDistVal = Collections.max(nDistVal);
Collections.sort(nDistVal);
sortedNImagePath = new ArrayList<String>();
for (int n = 0; n < nDistVal.size(); n++) {
int index = nstore.indexOf(nDistVal.get(n));
sortedNImagePath.add(nImagePath.get(index));
sortedNImageDistanceValues.add(String.valueOf(nDistVal.get(n) / maxDistVal));
String filePath = sortedNImagePath.get(0);
String minDistanceImg = sortedNImageDistanceValues.get(n);
FileNameFromPath = filePath.substring(filePath.lastIndexOf("/") + 1);
System.out.println("Distance values -> " + FileNameFromPath.toString());
System.out.println("Distance values -> " + minDistanceImg.toString());
}
} catch (Exception ex) {
String x = ex.getMessage();
System.out.println("ERORR" + x);
}
if (in != null) try {
in.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
Intent imgSearchedCoinNameIntent = new Intent(SearchByImageActivity.this, ImageSearchedCoinActivity.class);
imgSearchedCoinNameIntent.putExtra("imgSearchedCoinName", FileNameFromPath);
startActivity(imgSearchedCoinNameIntent);
}
}
};
Thread t = new Thread(runner, "Code Executer");
t.start();
}
}
If I put the "Waiting..." Toast after the FindSimilarRequestedImage() the toast will show up, but I need the toast show immediately after clicking on the btnSearchImg.
NOTE: Also in the dateiLesenStringBuilder() I removed the thread t that this part of code runs in normal flow and serial, but nothing changes!
Instead of toast use logcat to see if they run sequentially or not, maybe toast takes time to run
I solved this problem by putting the part of code in delay like below:
private void FindSimilarRequestedImage() {
if (ivGalleryImgLoad.getDrawable() != null) {
pbImgRetrvialProccess.setVisibility(View.VISIBLE);
Toasty.success(getBaseContext(), "Waiting ...", Toast.LENGTH_LONG).show();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
File loadedImageFilePath = new File(getRealPathFromURI(selectedImageUri));
queryFeatureX = uniformQuantization(loadedImageFilePath);
dateiLesenStringBuilder();
}
}, 5000);
} else {
Toasty.error(getBaseContext(), "first pick image from gallary", Toast.LENGTH_LONG).show();
}
}
Now before destroying activity throw functions, I first show the toast, then run other functions!
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.
I have created an application where one can view images. The problem I am facing is that when I use ".nomedia" in folder it hides images from gallery and images are also hidden in my application. I need a method with help of which images can remain hidden from gallery but shown in my application. I am accessing images using path of folder.
Code:
public class SdActivity extends Activity implements
MediaScannerConnectionClient {
public String[] allFiles;
private String SCAN_PATH;
private static final String FILE_TYPE = "*/*";
private MediaScannerConnection conn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
File folder = new File("/sdcard/DCIM");
allFiles = folder.list();
// uriAllFiles= new Uri[allFiles.length];
for (int i = 0; i < allFiles.length; i++) {
Log.d("all file path" + i, allFiles[i] + allFiles.length);
}
// Uri uri= Uri.fromFile(new
// File(Environment.getExternalStorageDirectory().toString()+"/yourfoldername/"+allFiles[0]));
SCAN_PATH = Environment.getExternalStorageDirectory().toString()
+ "/yourfoldername/" + allFiles[0];
Log.d("SCAN PATH", "Scan Path " + SCAN_PATH);
Button scanBtn = (Button) findViewById(R.id.buttonLoadPicture);
scanBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startScan();
}
});
}
private void startScan() {
Log.d("Connected", "success" + conn);
if (conn != null) {
conn.disconnect();
}
conn = new MediaScannerConnection(this, this);
conn.connect();
}
#Override
public void onMediaScannerConnected() {
Log.d("onMediaScannerConnected", "success" + conn);
conn.scanFile(SCAN_PATH, FILE_TYPE);
}
#Override
public void onScanCompleted(String path, Uri uri) {
try {
Log.d("onScanCompleted", uri + "success" + conn);
if (uri != null) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
}
} finally {
conn.disconnect();
conn = null;
}
}
}
I have made an activity In that I am having three relative Layouts and i am making them visible and gone as per needed.Now I have one ListView Called BuyingRequestList and for that i have made customeAdapter ,Now I have put a clickEvent of CustomAdapter's textView,Now what i need is when I click on the ListItem's textView "Quote" one relative layout "quote_view" is only visible and other two layouts should be invisible,My code is as below:
BuyingRequest.java
public class BuyingreqActivity extends Activity implements OnClickListener {
Button viewReq, postReq;
EditText productName;
TextView productCategory;
TextView expTime;
TextView productDesc;
TextView estOrderQty;
ImageView proImg;
Button send;
ImageView iv_fav_menu;
private int flag = 1;
ScrollView scr_post;
RelativeLayout scr_view;
RelativeLayout quote_view;
private ProgressDialog pDialog;
String viewURL, postURL;
JSONObject jsonObj;
JSONArray requestes = null;
ArrayList<HashMap<String, String>> reqList;
private BuyingRequestAdapter buyingRequestContent;
RelativeLayout rl_botm;
ListView lv;
Header header;
Calendar dateandtime;
private static final int PICK_FROM_CAMERA = 100;
private static final int PICK_FROM_GALLERY = 200;
private Uri picUri;
int la, lo;
final int CAMERA_CAPTURE = 1;
private static String fileName;
Intent in = null;
ListView quoteList;
private String imagePath;
private Uri imageUri;
String buyer_request_id, reqID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_buying_request);
InitializeView();
productCategory.setOnClickListener(this);
send.setOnClickListener(this);
expTime.setOnClickListener(this);
proImg.setOnClickListener(this);
dateandtime = Calendar.getInstance(Locale.US);
header.back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
reqList = new ArrayList<HashMap<String, String>>();
viewReq.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
flag = 2;
reqList.clear();
iv_fav_menu.setBackgroundResource(R.drawable.tab_two_fav);
new GetBuyingReqList().execute();
scr_view.setVisibility(View.VISIBLE);
rl_botm.setVisibility(View.GONE);
scr_post.setVisibility(View.GONE);
}
});
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
in = new Intent(getApplicationContext(), BuyingRequestDetailActivity.class);
// getting ProductId from the tag...
reqID = reqList.get(position).get(Const.TAG_BUYING_REQUEST_ID);
System.out.println(":::::::::::::::;;THE INTENT FOR THE resuest DETIALS ACTIVITY=================" + reqID);
in.putExtra(Const.TAG_BUYING_REQUEST_ID, reqID);
startActivity(in);
}
});
postReq.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
flag = 1;
iv_fav_menu.setBackgroundResource(R.drawable.tab_one_fav);
scr_post.setVisibility(View.VISIBLE);
rl_botm.setVisibility(View.VISIBLE);
scr_view.setVisibility(View.GONE);
}
});
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv_pro_cat:
break;
case R.id.tv_pro_exp_tym:
DatePickerDailog dp = new DatePickerDailog(BuyingreqActivity.this, dateandtime, new DatePickerDailog.DatePickerListner() {
#Override
public void OnDoneButton(Dialog datedialog, Calendar c) {
datedialog.dismiss();
dateandtime.set(Calendar.YEAR, c.get(Calendar.YEAR));
dateandtime.set(Calendar.MONTH, c.get(Calendar.MONTH));
dateandtime.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH));
expTime.setText(new SimpleDateFormat("yyyy-MM-dd").format(c.getTime()));
}
#Override
public void OnCancelButton(Dialog datedialog) {
// TODO Auto-generated method stub
datedialog.dismiss();
}
});
dp.show();
break;
case R.id.btn_send:
new postBuyingReqList().execute();
break;
case R.id.iv_img:
showCustomeAlert2(BuyingreqActivity.this, "Yehki", "From Camera", "From Gallery");
break;
}
}
#SuppressWarnings("deprecation")
private void showCustomeAlert2(Context context, String title, String rightButton, String leftButton) {
final Dialog dialog = new Dialog(BuyingreqActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
dialog.getWindow().setLayout(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
dialog.setContentView(R.layout.popup_alert);
dialog.setCancelable(false);
final ImageView btn_lft = (ImageView) dialog.findViewById(R.id.iv_left);
final ImageView btn_rgt = (ImageView) dialog.findViewById(R.id.iv_right);
final Button cancel = (Button) dialog.findViewById(R.id.btn_cancle);
final TextView btn_left = (TextView) dialog.findViewById(R.id.btnLeft);
final TextView btn_right = (TextView) dialog.findViewById(R.id.btnRight);
btn_left.setText(leftButton);
btn_right.setText(rightButton);
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
btn_rgt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
System.out.println("=========== perform click ==============");
String mediaStorageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath();
fileName = "user_" + Pref.getValue(BuyingreqActivity.this, Const.PREF_USER_ID, 0) + "_" + System.currentTimeMillis() + ".png";
imageUri = Uri.fromFile(new File(Const.DIR_USER + "/" + fileName));
System.out.println(" PATH ::: " + imageUri);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(cameraIntent, CAMERA_CAPTURE);
} catch (ActivityNotFoundException anfe) {
String errorMessage = "Whoops - your device doesn't support capturing images!";
}
dialog.dismiss();
}
});
btn_lft.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
// call android default gallery
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// ******** code for crop image
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
try {
intent.putExtra("return-data", true);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_GALLERY);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
dialog.dismiss();
}
});
dialog.show();
}
void InitializeView() {
iv_fav_menu = (ImageView) findViewById(R.id.iv_fav_menu);
viewReq = (Button) findViewById(R.id.btn_view);
postReq = (Button) findViewById(R.id.btn_post);
scr_post = (ScrollView) findViewById(R.id.scr_post);
scr_view = (RelativeLayout) findViewById(R.id.scr_view);
quote_view = (RelativeLayout) findViewById(R.id.quote_view);
lv = (ListView) findViewById(R.id.req_list);
rl_botm = (RelativeLayout) findViewById(R.id.rl_botm);
header = (Header) findViewById(R.id.headerBuying);
header.title.setText("Post Buying Request");
proImg = (ImageView) findViewById(R.id.iv_img);
quoteList = (ListView) findViewById(R.id.quote_list);
productName = (EditText) findViewById(R.id.et_pro_name);
productCategory = (TextView) findViewById(R.id.tv_pro_cat);
expTime = (TextView) findViewById(R.id.tv_pro_exp_tym);
productDesc = (EditText) findViewById(R.id.et_pro_desc);
estOrderQty = (TextView) findViewById(R.id.et_est_qty);
send = (Button) findViewById(R.id.btn_send);
}
/*
* getting buying request list...!!!
*/
private class GetBuyingReqList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(BuyingreqActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
String query = "?customer_id=" + Pref.getValue(BuyingreqActivity.this, Const.PREF_CUSTOMER_ID, "");
query = query.replace(" ", "%20");
viewURL = Const.API_BUYING_REQUEST_LIST + query;
BackendAPIService sh = new BackendAPIService();
System.out.println(":::::::::::::::::::ADDRESS URL:::::::::::::::::" + viewURL);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(viewURL, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
if (jsonObj.has(Const.TAG_BUYING_REQUEST)) {
System.out.println("::::::::::::::::true::::::::::::::::" + jsonObj.has(Const.TAG_ADDRESS_LIST));
requestes = jsonObj.getJSONArray(Const.TAG_BUYING_REQUEST);
if (requestes != null && requestes.length() != 0) {
// looping through All Contacts
System.out.println(":::::::::::FLAG IN SUB:::::::::::" + flag);
for (int i = 0; i < requestes.length(); i++) {
JSONObject c = requestes.getJSONObject(i);
buyer_request_id = c.getString(Const.TAG_BUYING_REQUEST_ID);
System.out.println(":::::::::::::::MY buying request:::::::::::::" + buyer_request_id);
String subject = c.getString(Const.TAG_PRODUCT_NAME);
String date_modified = c.getString(Const.TAG_DATE_MODIFIED);
String expired_date = c.getString(Const.TAG_EXPIRY_DATE);
String quote_count = c.getString(Const.TAG_QUOTE_COUNT);
String buying_request_status = c.getString(Const.TAG_BUYING_REQUEST_STATUS);
HashMap<String, String> request = new HashMap<String, String>();
request.put(Const.TAG_BUYING_REQUEST_ID, buyer_request_id);
request.put(Const.TAG_PRODUCT_NAME, subject);
request.put(Const.TAG_DATE_MODIFIED, date_modified);
request.put(Const.TAG_EXPIRY_DATE, expired_date);
request.put(Const.TAG_QUOTE_COUNT, quote_count);
request.put(Const.TAG_BUYING_REQUEST_STATUS, buying_request_status);
reqList.add(request);
System.out.println("::::::::::::::::Is filled:::::::::::" + reqList.size());
}
}
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
*
* */
buyingRequestContent = new BuyingRequestAdapter(BuyingreqActivity.this, reqList);
lv.setAdapter(buyingRequestContent);
}
}
/*
* getting qoute List...!!!
*/
private class GetQuoteList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(BuyingreqActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
String query = "?customer_id=" + Pref.getValue(BuyingreqActivity.this, Const.PREF_CUSTOMER_ID, "") + "&buyer_request_id=" + reqID;
query = query.replace(" ", "%20");
viewURL = Const.API_QUOTE_RECIEVED + query;
BackendAPIService sh = new BackendAPIService();
System.out.println(":::::::::::::::::::ADDRESS URL:::::::::::::::::" + viewURL);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(viewURL, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
if (jsonObj.has(Const.TAG_BUYING_REQUEST)) {
System.out.println("::::::::::::::::true::::::::::::::::" + jsonObj.has(Const.TAG_ADDRESS_LIST));
requestes = jsonObj.getJSONArray(Const.TAG_BUYING_REQUEST);
if (requestes != null && requestes.length() != 0) {
// looping through All Contacts
System.out.println(":::::::::::FLAG IN SUB:::::::::::" + flag);
for (int i = 0; i < requestes.length(); i++) {
JSONObject c = requestes.getJSONObject(i);
buyer_request_id = c.getString(Const.TAG_BUYING_REQUEST_ID);
System.out.println(":::::::::::::::MY buying request:::::::::::::" + buyer_request_id);
String subject = c.getString(Const.TAG_PRODUCT_NAME);
String date_modified = c.getString(Const.TAG_DATE_MODIFIED);
String expired_date = c.getString(Const.TAG_EXPIRY_DATE);
String quote_count = c.getString(Const.TAG_QUOTE_COUNT);
String buying_request_status = c.getString(Const.TAG_BUYING_REQUEST_STATUS);
HashMap<String, String> request = new HashMap<String, String>();
request.put(Const.TAG_BUYING_REQUEST_ID, buyer_request_id);
request.put(Const.TAG_PRODUCT_NAME, subject);
request.put(Const.TAG_DATE_MODIFIED, date_modified);
request.put(Const.TAG_EXPIRY_DATE, expired_date);
request.put(Const.TAG_QUOTE_COUNT, quote_count);
request.put(Const.TAG_BUYING_REQUEST_STATUS, buying_request_status);
reqList.add(request);
System.out.println("::::::::::::::::Is filled:::::::::::" + reqList.size());
}
}
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
*
* */
buyingRequestContent = new BuyingRequestAdapter(BuyingreqActivity.this, reqList);
lv.setAdapter(buyingRequestContent);
}
}
/*
* post Buying Request api()...!!!
*/
private class postBuyingReqList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(BuyingreqActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
postURL = Const.API_BUYING_REQUEST + "?customer_id=" + Pref.getValue(BuyingreqActivity.this, Const.PREF_CUSTOMER_ID, "") + "&product_name=" + productName.getText().toString().trim()
+ "&category_id=1&expire_time=" + expTime.getText().toString() + "&detail_desc=" + productDesc.getText().toString().trim() + "&esti_ordr_qty="
+ estOrderQty.getText().toString().trim() + "&esti_ordr_qty_unit=1&filename=abc.jpg&image=abc.png";
// Creating service handler class instance
postURL = postURL.replace(" ", "%20");
BackendAPIService sh = new BackendAPIService();
System.out.println(":::::::::::::::::::post buying request URL:::::::::::::::::" + postURL);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(postURL, BackendAPIService.POST);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
if (jsonObj.get("status").equals("success")) {
flag = 0;
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Intent i;
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
if (flag == 0) {
Utils.showCustomeAlertValidation(BuyingreqActivity.this, "Request Posted", "Yehki", "OK");
clearViews();
} else {
Toast.makeText(BuyingreqActivity.this, "Buying Request has not been posted", 0).show();
}
/**
* Updating parsed JSON data into ListView
*
* */
}
}
void clearViews() {
productName.setText("");
productDesc.setText("");
estOrderQty.setText("");
expTime.setText("Expiration Time");
proImg.setImageResource(R.drawable.noimage);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_CAPTURE) { // for camera
try {
System.out.println("============= FILENAME :: " + fileName);
if (new File(Const.DIR_USER + "/" + fileName).exists()) {
performCrop();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) { // for crop image
try {
if (data != null) {
Bundle extras = data.getExtras();
Bitmap thePic = extras.getParcelable("data");
Utils.createDirectoryAndSaveFile(thePic, Const.DIR_USER + "/" + fileName);
// pro_pic.setImageBitmap(thePic);
#SuppressWarnings("deprecation")
Drawable dra = (Drawable) new BitmapDrawable(thePic);
proImg.setImageDrawable(dra);
proImg.setScaleType(ScaleType.FIT_XY);
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == PICK_FROM_GALLERY && resultCode == RESULT_OK) {
if (data != null) {
/*
* fileName = Const.DIR_USER + "/" + "user_" +
* Pref.getValue(ProfileActivity.this, Const.PREF_USER_ID, 0) +
* "_" + System.currentTimeMillis() + ".png";
*/
fileName = "user_" + Pref.getValue(BuyingreqActivity.this, Const.PREF_USER_ID, 0) + "_" + System.currentTimeMillis() + ".png";
Bundle extras2 = data.getExtras();
Bitmap photo = extras2.getParcelable("data");
Utils.createDirectoryAndSaveFile(photo, Const.DIR_USER + "/" + fileName);
ImageView picView = (ImageView) findViewById(R.id.iv_img);
picView.setImageBitmap(photo);
}
}
}
private void performCrop() {
try {
System.out.println("============= AFTER FILENAME :: " + fileName);
Intent cropIntent = new Intent("com.android.camera.action.CROP");
imageUri = Uri.fromFile(new File(Const.DIR_USER + "/" + fileName));
cropIntent.setDataAndType(imageUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("outputX", 200);// 256
cropIntent.putExtra("outputY", 200);
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, 2);
}
catch (ActivityNotFoundException anfe) {
String errorMessage = "Whoops - your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
}
Adaptrer.java
package com.epe.yehki.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.epe.yehki.ui.BuyingreqActivity;
import com.epe.yehki.ui.BuyingreqActivity.GetQuoteList;
import com.epe.yehki.util.Const;
import com.example.yehki.R;
public class BuyingRequestAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> BuyingRequestArray;
private Context mContext;
public BuyingRequestAdapter(Context paramContext, ArrayList<HashMap<String, String>> productList) {
this.mContext = paramContext;
this.BuyingRequestArray = productList;
}
public int getCount() {
return this.BuyingRequestArray.size();
}
public Object getItem(int paramInt) {
return Integer.valueOf(paramInt);
}
public long getItemId(int paramInt) {
return paramInt;
}
#SuppressWarnings("static-access")
public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) {
LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext.getSystemService("layout_inflater");
Viewholder localViewholder = null;
if (paramView == null) {
paramView = localLayoutInflater.inflate(R.layout.raw_buying_req, paramViewGroup, false);
localViewholder = new Viewholder();
localViewholder.sub = ((TextView) paramView.findViewById(R.id.sub));
localViewholder.expDate = ((TextView) paramView.findViewById(R.id.exp_date));
localViewholder.quote = ((TextView) paramView.findViewById(R.id.quote));
localViewholder.status = ((TextView) paramView.findViewById(R.id.status));
localViewholder.lastUpdate = ((TextView) paramView.findViewById(R.id.last_updated));
paramView.setTag(localViewholder);
} else {
localViewholder = new Viewholder();
localViewholder = (Viewholder) paramView.getTag();
}
System.out.println(":::::::::::::::values:::::::::::::::" + BuyingRequestArray.get(paramInt).get(Const.TAG_PRODUCT_NAME));
localViewholder.sub.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_PRODUCT_NAME));
localViewholder.expDate.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_EXPIRY_DATE));
localViewholder.lastUpdate.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_DATE_MODIFIED));
localViewholder.quote.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_QUOTE_COUNT));
localViewholder.quote.setTextColor(Color.parseColor("#0000ff"));
localViewholder.status.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_BUYING_REQUEST_STATUS));
localViewholder.quote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/* new (BuyingreqActivity)GetQuoteList.execute();*/
}
});
return paramView;
}
static class Viewholder {
TextView sub;
TextView lastUpdate;
TextView expDate;
TextView quote;
TextView status;
}
}
Create an interface class, say ViewHider
public interface ViewHider{
public void hideView(String clickedtext);
}
have your activity implement this.
In your activity add unimplemented method and write inside it like
#Override
public void hideView(String clickedtext) {
if(clickedtext.equals("Quote"){
layoutName.setVisibility(View.GONE);
}
}
In your adapter, create an object of ViewHider class
ViewHider viewHider;
then, set click listener for the text view you want and inside that call the method
if(textView.getText.equals("Quote")
viewHider.hideView("Quote");
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.