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.
Related
Hi Hello to everyone i am developing one app where i am using service to upload multipal images to server for uploading multipal images even if app is closed from background.
But i want to call one function but i am unable to call that function please help me.
UploadPhotos.java
public class UploadPhotos extends AppCompatActivity {
UploadService mBoundService;
boolean mServiceBound = false;
Context context;
SelectPaper paperSession;
private CoordinatorLayout coordinatorLayout;
SelectLab labSession;
SessionManager session;
String strSize,strType,str_username,strMRP,strPrice,strlab,strcity,strdel_type,album_type;
MaterialEditText ppr_size,ppr_type,mrp,disPrice;
SelectedAdapter_Test selectedAdapter;
long totalprice=0;
int i=0;
ProgressBar pb;
String imageName,user_mail,total;
GridView UploadGallery;
Handler handler;
ArrayList<CustomGallery> listOfPhotos;
ImageLoader imageLoader;
String Send[];
Snackbar snackbar;
OrderId orderidsession;
AlertDialog dialog;
Button btnGalleryPickup, btnUpload;
TextView noImage;
String abc;
NotificationManager manager;
Notification.Builder builder;
ArrayList<CustomGallery> dataT;
Notification myNotication;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_photos);
context = this;
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
final ActionBar ab = getSupportActionBar();
assert ab != null;
ab.setDisplayHomeAsUpEnabled(true);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.main_content);
labSession = new SelectLab(getApplicationContext());
paperSession = new SelectPaper(getApplicationContext());
orderidsession=new OrderId(getApplicationContext());
session = new SessionManager(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
user_mail = user.get(SessionManager.KEY_EMAIL);
noImage = (TextView)findViewById(R.id.noImage);
final String symbol = getResources().getString(R.string.rupee_symbol);
HashMap<String, String> paper = paperSession.getPaperDetails();
strSize = paper.get(SelectPaper.KEY_SIZE);
strType = paper.get(SelectPaper.KEY_TYPE);
strdel_type=paper.get(SelectPaper.DEL_TYPE);
HashMap<String, String> lab = labSession.getLabDetails();
strMRP = lab.get(SelectLab.KEY_MRP);
strPrice = lab.get(SelectLab.KEY_PRICE);
strlab = lab.get(SelectLab.KEY_LAB);
strcity = lab.get(SelectLab.KEY_CITY);
str_username=lab.get(SelectLab.KEY_USERNAME);
ppr_size = (MaterialEditText) findViewById(R.id.paper_size);
ppr_type = (MaterialEditText) findViewById(R.id.paper_type);
mrp = (MaterialEditText) findViewById(R.id.MRP);
disPrice = (MaterialEditText) findViewById(R.id.discount_price);
ppr_size.setText(strSize);
ppr_type.setText(strType);
mrp.setText(symbol + " " + strMRP);
disPrice.setText(symbol + " " + strPrice);
initImageLoader();
init();
}
private void initImageLoader() {
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheOnDisc().imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
.bitmapConfig(Bitmap.Config.RGB_565).build();
ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(
this).defaultDisplayImageOptions(defaultOptions).memoryCache(
new WeakMemoryCache());
ImageLoaderConfiguration config = builder.build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
}
private void init() {
handler = new Handler();
UploadGallery = (GridView) findViewById(R.id.uploadGallery);
UploadGallery.setFastScrollEnabled(true);
selectedAdapter = new SelectedAdapter_Test(getApplicationContext(), imageLoader);
UploadGallery.setAdapter(selectedAdapter);
btnGalleryPickup = (Button) findViewById(R.id.btnSelectPhoto);
btnGalleryPickup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Action.ACTION_MULTIPLE_PICK);
startActivityForResult(i, 200);
}
});
btnUpload = (Button) findViewById(R.id.btn_upload);
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listOfPhotos = selectedAdapter.getAll();
if (listOfPhotos != null && listOfPhotos.size() > 0) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
abc = sdf.format(new Date());
Log.d("Orderid Session", ""+abc);
abc="EPP"+abc;
orderidsession.CreateOrderId(abc);
Toast.makeText(getApplicationContext(),""+abc,Toast.LENGTH_LONG).show();
//progressDialog = ProgressDialog.show(UploadPhotos.this, "", "Uploading files to server.....", false);
//AlertDialog dialog;;
dialog = new SpotsDialog(UploadPhotos.this);
dialog.show();
Thread thread = new Thread(new Runnable() {
public void run() {
Intent in = new Intent(UploadPhotos.this, UploadService.class);
in.putExtra("listof",dataT);
in.putExtra("strsize",strSize);
in.putExtra("strtype",strType);
in.putExtra("user_mail",user_mail);
in.putExtra("strmrp",strMRP);
in.putExtra("strprice",strPrice);
in.putExtra("strlab",strlab);
in.putExtra("strcity",strcity);
in.putExtra("strdel_type",strdel_type);
in.putExtra("strusername",str_username);
in.putExtra("foldername",abc);
startService(in);
bindService(in, mServiceConnection, Context.BIND_AUTO_CREATE);
// doFileUpload();
runOnUiThread(new Runnable() {
public void run() {
if (dialog.isShowing()) {
dialog.dismiss();
totalprice=0;
}
}
});
}
});
thread.start();
}else{
Toast.makeText(getApplicationContext(),"Please select two files to upload.", Toast.LENGTH_SHORT).show();
}
}
});
UploadGallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CustomGallery objDetails = (CustomGallery) selectedAdapter.getItem(position);
selectedAdapter.getItem(position);
// selectedAdapter.Pbbar(view );
Toast.makeText(getApplicationContext(), "Position : " + position + " Path : " + objDetails.sdcardPath, Toast.LENGTH_SHORT).show();
//selectedAdapter.changeSelection(view, position);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 200 && resultCode == Activity.RESULT_OK) {
String[] all_path = data.getStringArrayExtra("all_path");
noImage.setVisibility(View.GONE);
UploadGallery.setVisibility(View.VISIBLE);
dataT = new ArrayList<CustomGallery>();
for (String string : all_path) {
CustomGallery item = new CustomGallery();
item.sdcardPath = string;
dataT.add(item);
}
Log.d("DATAt",dataT.toString());
selectedAdapter.addAll(dataT);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_upload_photos, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
private ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
mServiceBound = false;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
UploadService.MyBinder myBinder = (UploadService.MyBinder) service;
mBoundService = myBinder.getService();
mServiceBound = true;
}
};
}
SelectedAdapter_Test.java
public class SelectedAdapter_Test extends BaseAdapter{
private Context mContext;
private LayoutInflater inflater;
private ArrayList<CustomGallery> data = new ArrayList<CustomGallery>();
ImageLoader imageLoader;
private boolean isActionMultiplePick;
public SelectedAdapter_Test(Context c, ImageLoader imageLoader) {
mContext = c;
inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.imageLoader = imageLoader;
// clearCache();
}
public class ViewHolder {
ImageView imgQueue;
ImageView imgEdit;
EditText qty;
Button ok;
ProgressBar pb;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int i) {
return data.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
public void changeSelection(View v, int position) {
if (data.get(position).isSeleted) {
data.get(position).isSeleted = false;
((ViewHolder) v.getTag()).imgEdit.setVisibility(View.GONE);
((ViewHolder) v.getTag()).qty.setVisibility(View.GONE);
((ViewHolder) v.getTag()).ok.setVisibility(View.GONE);
} else {
data.get(position).isSeleted = true;
((ViewHolder) v.getTag()).qty.setVisibility(View.VISIBLE);
((ViewHolder) v.getTag()).ok.setVisibility(View.VISIBLE);
((ViewHolder) v.getTag()).imgEdit.setVisibility(View.VISIBLE);
}
}
public void Pbbar(View v) {
((ViewHolder)v.getTag()).pb.setVisibility(View.VISIBLE);
}
#Override
public View getView(final int i, View convertView, ViewGroup viewGroup) {
final ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.inflate_photo_upload, null);
holder = new ViewHolder();
holder.pb=(ProgressBar)convertView.findViewById(R.id.pb_image_upload);
holder.imgQueue = (ImageView) convertView.findViewById(R.id.imgQueue);
holder.imgEdit = (ImageView) convertView.findViewById(R.id.imgedit);
holder.qty = (EditText)convertView.findViewById(R.id.quantity);
holder.ok = (Button)convertView.findViewById(R.id.btn_ok);
holder.imgEdit.setVisibility(View.GONE);
holder.qty.setVisibility(View.GONE);
holder.ok.setVisibility(View.GONE);
holder.ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
data.get(i).qty = 1;
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//holder.imgQueue.setTag(position);
imageLoader.displayImage("file://" + data.get(i).sdcardPath, holder.imgQueue, new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
holder.imgQueue.setImageResource(R.drawable.no_media);
super.onLoadingStarted(imageUri, view);
}
});
if (isActionMultiplePick) {
holder.imgEdit.setSelected(data.get(i).isSeleted);
holder.qty.setSelected(data.get(i).isSeleted);
holder.ok.setSelected(data.get(i).isSeleted);
Log.d("Position Data", data.get(i).toString());
Log.d("Position", String.valueOf(i));
}
return convertView;
}
public void addAll(ArrayList<CustomGallery> files) {
try {
this.data.clear();
this.data.addAll(files);
} catch (Exception e) {
e.printStackTrace();
}
notifyDataSetChanged();
}
public ArrayList getAll(){
return data;
}
}
and here is the service
public class UploadService extends Service {
private static String LOG_TAG = "BoundService";
private IBinder mBinder = new MyBinder();
ArrayList<CustomGallery> listOfPhotos;
int i=0;
ImageLoader imageLoader;
NotificationManager manager;
Notification myNotication;
String response_str=null;
long totalprice=0;
Notification.Builder builder;
SelectedAdapter_Test selectedAdapter;
String strsize,strtype,usermail,total,strmrp,strprice,strlab,strcity,abc,strdel_type,struname,imageName;
#Nullable
#Override
public IBinder onBind(Intent intent) {
Log.v(LOG_TAG, "in onBind");
return mBinder;
}
#Override
public void onRebind(Intent intent) {
Log.v(LOG_TAG, "in onRebind");
super.onRebind(intent);
}
#Override
public boolean onUnbind(Intent intent) {
Log.v(LOG_TAG, "in onUnbind");
return true;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
selectedAdapter = new SelectedAdapter_Test(getApplicationContext(), imageLoader);
Toast.makeText(UploadService.this, "Service Started ", Toast.LENGTH_SHORT).show();
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
listOfPhotos = (ArrayList<CustomGallery>) intent.getSerializableExtra("listof");
strsize = intent.getStringExtra("strsize");
strtype = intent.getStringExtra("strtype");
usermail = intent.getStringExtra("user_mail");
strmrp = intent.getStringExtra("strmrp");
strprice = intent.getStringExtra("strprice");
strlab = intent.getStringExtra("strlab");
strcity = intent.getStringExtra("strcity");
struname = intent.getStringExtra("strusername");
strdel_type = intent.getStringExtra("strdel_type");
abc = intent.getStringExtra("foldername");
// selectedAdapter.Pbbar(view);
Intent intn = new Intent("com.dhruva.eprintpost.digitalPrinting");
PendingIntent pendingIntent = PendingIntent.getActivity(UploadService.this, 1, intn, 0);
builder = new Notification.Builder(UploadService.this);
builder.setAutoCancel(true);
builder.setOngoing(true);
builder.setContentTitle("Uploading Photos");
builder.setContentText("Uploading PhotoPrinting Images");
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setContentIntent(pendingIntent);
builder.setOngoing(true);
for( i = 0 ; i<listOfPhotos.size();i++) {
try {
File f = new File(listOfPhotos.get(i).sdcardPath.toString());
//Toast.makeText(UploadService.this, "aa "+listOfPhotos.get(i).sdcardPath, Toast.LENGTH_SHORT).show();
int j=i+1;
builder.setSubText("Uploading " + j + " of " + listOfPhotos.size() + " image"); //API level 16
j++;
Toast.makeText(UploadService.this, "i is = "+i, Toast.LENGTH_SHORT).show();
builder.build();
myNotication = builder.getNotification();
manager.notify(11, myNotication);
imageName = f.getName();
totalprice = totalprice + Long.parseLong(strprice);
total = String.valueOf(totalprice);
Log.v("Abhijit", "" + totalprice);
String responseString = null;
final HttpClient httpclient = new DefaultHttpClient();
final HttpPost httppost = new HttpPost("http://abcdefg.com/abcd/UploadFile?foldername=" + abc); //TODO - to hit URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
}
});
File sourceFile = new File(listOfPhotos.get(i).sdcardPath);
Toast.makeText(UploadService.this, "aa "+sourceFile.getName(), Toast.LENGTH_SHORT).show();
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
entity.addPart("foldername", new StringBody(abc));
entity.addPart("size",
new StringBody(strsize));
entity.addPart("type",
new StringBody(strtype));
entity.addPart("username",
new StringBody(usermail));
entity.addPart("total",
new StringBody(total));
entity.addPart("mrp",
new StringBody(strmrp));
entity.addPart("price",
new StringBody(strprice));
entity.addPart("lab",
new StringBody(strlab));
Toast.makeText(UploadService.this, "aa Ky Ho raha hai bhai", Toast.LENGTH_SHORT).show();
entity.addPart("city",
new StringBody(strcity));
entity.addPart("imagename",
new StringBody(imageName));
entity.addPart("deltype",
new StringBody(strdel_type));
String initflag = String.valueOf(i + 1);
entity.addPart("initflag",
new StringBody(initflag));
entity.addPart("lab_username",
new StringBody(struname));
// totalSize = entity.getContentLength();
httppost.setEntity(entity);
Thread thread = new Thread(new Runnable() {
public void run() {
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
response_str = EntityUtils.toString(r_entity);
if (r_entity != null) {
Toast.makeText(UploadService.this, "SSS"+response_str, Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}catch(Exception e)
{
e.printStackTrace();
}
}
});
thread.start();
Toast.makeText(UploadService.this, "SSS"+response_str, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
responseString = e.toString();
Toast.makeText(UploadService.this, "Exception Occured2 ", Toast.LENGTH_SHORT).show();
}catch(Exception e)
{
Toast.makeText(UploadService.this, "Exception Occured 3", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return Service.START_NOT_STICKY;
}
public class MyBinder extends Binder {
UploadService getService() {
return UploadService.this;
}
}
}
Here i want to call pbbar function from adapter class but i am unable to send view parameter to function from server.
Please help me i am new to android
another problem is that the value in notification is not changing it take last value of i throughout the execuation.
i want to update the value of i according to the successful upload image
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 am developing an android app based on GCM. The functionality is working perfectly, but I am running into an issue where when I am using the app and on the list screen, the list does not automatically refresh when the app receives a message from GCM. Notifications work fine, but I do not know how to get the message to appear in the list while I'm viewing it.
Here is my GcmBroadcastReceiver:
public class GcmBroadcastReceiver extends BroadcastReceiver {
static final String TAG = "GCMDemo";
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
private MessageDatabaseHelper MDH;
Context ctx;
#Override
public void onReceive(Context context, Intent intent) {
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
ctx = context;
String messageType = gcm.getMessageType(intent);
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
try {
sendNotification("Send error: " + intent.getExtras().toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
try {
sendNotification("Deleted messages on server: " +
intent.getExtras().toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
try {
if(intent.getExtras().getString("message") != null){
sendNotification(intent.getExtras().getString("message"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
setResultCode(Activity.RESULT_OK);
}
// Put the GCM message into a notification and post it.
private void sendNotification(String msg) throws JSONException {
mNotificationManager = (NotificationManager)
ctx.getSystemService(Context.NOTIFICATION_SERVICE);
SharedPreferences prefs1 = ctx.getSharedPreferences("UNIQUE", Context.MODE_PRIVATE);
int unique_id = prefs1.getInt("UNIQUE_ID", 0);
SharedPreferences.Editor editor = prefs1.edit();
unique_id++;
editor.putInt("UNIQUE_ID", unique_id);
editor.commit();
Log.v("TEST", "sharedprefs - " + prefs1.getInt("UNIQUE_ID", 0));
JSONObject JSdata = new JSONObject(msg);
String category = "";
String text = "";
String subject = "";
String from = "";
if(JSdata.getString("Category") != null){
Log.v("TEST", "CATEGORY - " + JSdata.getString("Category"));
category = JSdata.getString("Category");
}
if(JSdata.getString("Subject") != null){
Log.v("TEST", "SUBJECT - " + JSdata.getString("Subject"));
subject = JSdata.getString("Subject");
}
if(JSdata.getString("Message") != null){
Log.v("TEST", "Message - " + JSdata.getString("Message"));
text = JSdata.getString("Message");
}
if(JSdata.getString("From") != null){
Log.v("TEST", "FROM - " + JSdata.getString("From"));
from = JSdata.getString("From");
}
String dateTime = "";
Time now = new Time();
now.setToNow();
dateTime = (now.month + 1) + "/" + now.monthDay + " " + now.hour + ":" + now.minute;
Log.v("date", "date - " + dateTime);
Message message = new Message(1, category, text, subject, from, dateTime);
MDH = new MessageDatabaseHelper(ctx);
MDH.addMessage(message);
// new AsyncTask() {
// #Override
// protected String doInBackground(Object... arg0) {
// Intent mainIntent = new Intent(ctx, MainActivity.class);
// mainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// ctx.startActivity(mainIntent);
// Log.v("GCMDEMO", "background");
// return "";
// }
// }.execute(null, null, null);
Intent gcmIntent = new Intent(ctx, MessageActivity.class);
gcmIntent.putExtra("message1", message);
PendingIntent contentIntent = PendingIntent.getActivity(ctx, unique_id,
gcmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(ctx)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Choice Cloud Notification")
.setContentText(JSdata.getString("Subject") + " " + JSdata.getString("Category"))
.setAutoCancel(true);
NotificationCompat.InboxStyle big = new NotificationCompat.InboxStyle(
mBuilder);
big.setSummaryText(JSdata.getString("Subject") + " " + JSdata.getString("Category"));
big.addLine(JSdata.getString("Message"));
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(unique_id, big.build());
//mBuilder.setContentIntent(contentIntent);
//mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
And here is my MainActivity
public class MainActivity extends Activity{
private MessageDatabaseHelper MDH;
private boolean initialLaunch = false;
private StableArrayAdapter adapter;
private ListView listview;
private List<Message> mList;
private Spinner spinner;
public static final String EXTRA_MESSAGE = "message";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private static final String SENDER_ID = "469307705305"; //This is the project number under the API
static final String TAG = "GCMDemo";
GoogleCloudMessaging gcm;
AtomicInteger msgId = new AtomicInteger();
SharedPreferences prefs;
Context context;
String regid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplicationContext();
regid = getRegistrationId(context);
if (regid.length() == 0) {
registerBackground();
}
gcm = GoogleCloudMessaging.getInstance(this);
spinner = (Spinner) findViewById(R.id.category_spinner);
MDH = new MessageDatabaseHelper(this);
//On first launch of app, add some mock messages for testing
if(isInitialLaunch()){
setInitialLaunch(true);
Message m1 = new Message(1, "RateCenter", "rates are low", "Sub1", "From1", "7/31 8:45");
MDH.addMessage(m1);
SharedPreferences prefs1 = getSharedPreferences("UNIQUE", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs1.edit();
editor.putInt("UNIQUE_ID", 0);
editor.commit();
}
//Message m1 = new Message(1, "RateCenter", "rates are low", "Sub1", "From1");
//MDH.addMessage(m1);
//Grab all categories dynamically from database
List<String> cList = new ArrayList<String>();
cList = MDH.getAllCategories();
HashSet hs = new HashSet();
hs.addAll(cList);
cList.clear();
cList.addAll(hs);
//Add those categories to arraylist for use in spinner
List<String> categories = new ArrayList<String>();
//categories.add("Please select a category");
categories.add("All");
for(String s:cList){
categories.add(s);
}
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, categories);
// Specify the layout to use when the list of choices appears
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter1);
//add onitemselected listener to spinner
spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
//Refresh main activity with correct set of messages pertaining to category selected
String test1 = parent.getItemAtPosition(pos).toString();
String test2 = MyApplication.globalCategory;
if(!(test1.equals(test2))){
MyApplication.sPos = pos;
MyApplication.globalCategory = parent.getItemAtPosition(pos).toString();
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}});
//Creates a listview to be used to store messages
listview = (ListView) findViewById(R.id.list);
listview.setItemsCanFocus(false);
//grab messages from database for use in listview corresponding to category selected
mList = new ArrayList<Message>();
if(MyApplication.globalCategory.equals("All")){
mList = MDH.getAllMessages();
}
else {
mList = MDH.getMessagesWithCategory(MyApplication.globalCategory);
}
//instantiates adapter and adds it to listview
adapter = new StableArrayAdapter(this, mList);
listview.setAdapter(adapter);
listview.setClickable(true);
//adds click listener to list
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
Log.v("GCMDemo", "Registration id is - " + getRegistrationId(MainActivity.this));
Message clickedMessage = (Message)parent.getItemAtPosition(position);
clickedMessage.setUnread(false);
MDH.updateUnread(clickedMessage);
//starts new messageactivity, passing the message clicked on as an extra to the intent
listview.invalidateViews();
Intent startMessageActivityIntent = new Intent();
startMessageActivityIntent.putExtra("message1", clickedMessage);
startMessageActivityIntent.setClass(MainActivity.this,
MessageActivity.class);
startActivity(startMessageActivityIntent);
finish();
}
});
}
#SuppressWarnings("unchecked")
private void registerBackground() {
new AsyncTask() {
#Override
protected String doInBackground(Object... arg0) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regid = gcm.register(SENDER_ID);
msg = "Device registered, registration id=" + regid;
// Save the regid - no need to register again.
setRegistrationId(context, regid);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
Log.v("GCMDEMO", "GCMWHAT - " + msg);
return msg;
}
}.execute(null, null, null);
}
private void setRegistrationId(Context context, String regid) {
final SharedPreferences prefs = getGCMPreferences(context);
int appVersion = getAppVersion(context);
Log.v(TAG, "Saving regId on app version " + appVersion);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regid);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
}
private String getRegistrationId(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.length() == 0) {
Log.v(TAG, "Registration not found.");
return "";
}
// check if app was updated; if so, it must clear registration id to
// avoid a race condition if GCM sends a message
int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
Log.v(TAG, "App version changed");
return "";
}
return registrationId;
}
private int getAppVersion(Context context2) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (NameNotFoundException e) {
// should never happen
throw new RuntimeException("Could not get package name: " + e);
}
}
private SharedPreferences getGCMPreferences(Context context2) {
return getSharedPreferences(MainActivity.class.getSimpleName(),
Context.MODE_PRIVATE);
}
private class StableArrayAdapter extends ArrayAdapter<Message> {
//adapter class for use with listview, maps items to positions
//HashMap<Message, Integer> hMap = new HashMap<Message, Integer>();
private final Context context1;
private final List<Message> adaptList;
public StableArrayAdapter(Context cont,
List<Message> objects) {
super(context, R.layout.ccm_list_item, objects);
//for (int i = 0; i < objects.size(); i++) {
// hMap.put(objects.get(i), i);
//}
this.context1 = cont;
this.adaptList = new ArrayList<Message>();
this.adaptList.addAll(objects);
}
private class ViewHolder {
public TextView text;
public TextView text2;
public TextView textTime;
public CheckBox checkBox;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.ccm_list_item, null);
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context1
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
holder.text = (TextView) convertView.findViewById(R.id.rowText);
holder.text2 = (TextView) convertView.findViewById(R.id.rowText2);
holder.textTime = (TextView) convertView.findViewById(R.id.rowTextTime);
holder.checkBox = (CheckBox) convertView
.findViewById(R.id.listCheck);
holder.checkBox.setFocusable(false);
holder.checkBox.setFocusableInTouchMode(false);
convertView.setTag(holder);
holder.checkBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Message message = (Message)cb.getTag();
Toast.makeText(getApplicationContext(),
"Clicked on Checkbox: " + cb.getText() +
" is " + cb.isChecked(),
Toast.LENGTH_LONG).show();
//country.setSelected(cb.isChecked());
}
});
}
else {
holder = (ViewHolder) convertView.getTag();
}
int count = 0;
Message m1 = new Message();
if(MyApplication.globalCategory.equals("All")){
mList = MDH.getAllMessages();
for (Message m: mList) {
if(count == position){
m1 = m;
}
count++;
}
}
else {
mList = MDH.getMessagesWithCategory(MyApplication.globalCategory);
for (Message m: mList) {
if(count == position){
m1 = m;
}
count++;
}
}
if (m1.getUnread() == false) {
holder.text.setText(m1.toString());
holder.text2.setText(m1.getText());
holder.textTime.setText(m1.getTime());
convertView.setBackgroundColor(Color.LTGRAY);
} else {
holder.text.setText(m1.toString());
holder.text2.setText(m1.getText());
holder.textTime.setText(m1.getTime());
convertView.setBackgroundColor(Color.WHITE);
holder.text.setTypeface(null, Typeface.BOLD);
holder.text2.setTypeface(null, Typeface.BOLD);
}
holder.checkBox.setFocusable(false);
holder.checkBox.setFocusableInTouchMode(false);
holder.text.setFocusable(false);
holder.text.setFocusableInTouchMode(false);
((ViewGroup) convertView).setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
return convertView;
}
}
public void setInitialLaunch(boolean initialLaunch) {
SharedPreferences settings = getSharedPreferences("APPLAUNCH", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("APPLAUNCHKEY", false);
editor.commit();
this.initialLaunch = initialLaunch;
}
public boolean isInitialLaunch() {
SharedPreferences settings = getSharedPreferences("APPLAUNCH", 0);
this.initialLaunch = settings.getBoolean("APPLAUNCHKEY", true);
return initialLaunch;
}
#Override
protected void onStart() {
//on start, grabs message from database and updates adapter with changes to data
super.onStart();
if(MyApplication.globalCategory.equals("All")){
mList = MDH.getAllMessages();
for (Message m: mList) {
}
}
else {
mList = MDH.getMessagesWithCategory(MyApplication.globalCategory);
for (Message m: mList) {
}
}
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
adapter.notifyDataSetChanged() ;
}
});
spinner.setSelection(MyApplication.sPos);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
super.onCreateOptionsMenu(menu);
return true;
}
//option item about added to menu and starts aboutactivity when selected
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_settings) {
Intent startActivityIntent = new Intent(this,
AboutActivity.class);
startActivity(startActivityIntent);
return true;
}
return true;
}
}
I have made a program in which i am fetching list of all my Facebook Friends with their name, dob and profile picture, but i have decided to use tabs in my existing program therefore, i have also written code for that, but whenever i run my app, every time i am getting tabs but not getting list of friends..
In my case i am not getting FriendsList Activity data in TabSample Class, why?
SplashScreen.java:-
private final static int FACEBOOK_AUTHORIZE_ACTIVITY_RESULT_CODE = 0;
private final static int FRIENDS_LIST_ACTIVITY = 1;
public void onRequestReceived(int result, String message) {
Log.d(LOG_TAG, "onRequestReceived(" + result + ")");
if(isFinishing())
return;
switch (result) {
case FacebookRequest.COMPLETED:
Intent intent = new Intent(this, com.chr.tatu.sample.friendslist.TabSample.class);
intent.putExtra("FRIENDS", message);
while (System.currentTimeMillis() - startTime < DELAY) {
try { Thread.sleep(50); } catch (Exception e) {}
}
startActivityForResult(intent, FRIENDS_LIST_ACTIVITY);
isLoadingFriends = false;
break;
case FacebookRequest.IO_EXCEPTION:
case FacebookRequest.FILE_NOT_FOUND_EXCEPTION:
case FacebookRequest.MALFORMED_URL_EXCEPTION:
case FacebookRequest.FACEBOOK_ERROR:
FacebookUtility.displayMessageBox(this, this.getString(R.string.friends_error));
onButton();
break;
}
}
FriendsList.java:-
public class FriendsList extends Activity implements FacebookRequest, OnItemClickListener {
private static String LOG_TAG = "FriendsList";
private static JSONArray jsonArray;
private static ListView friendsList;
private Handler mHandler;
private Button saveGreeting;
public void onCreate(Bundle savedInstanceState) {
mHandler = new Handler();
super.onCreate(savedInstanceState);
try {
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
getActionBar().hide();
} catch (Exception e) {}
setContentView(R.layout.friends_list_screen);
try {
setProgressBarIndeterminateVisibility(false);
} catch (Exception e) {}
init();
saveGreeting = (Button) findViewById(R.id.greeting);
saveGreeting.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
customGreeting(v);
}
});
}
public void customGreeting(View v) {
Intent myWebLink = new Intent(android.content.Intent.ACTION_VIEW);
myWebLink.setData(Uri.parse("http://google.com/"));
startActivity(myWebLink);
}
#Override
public void onDestroy() {
super.onDestroy();
exit();
}
private void exit() {
if (friendsList != null)
friendsList.setAdapter(null);
friendsList = null;
jsonArray = null;
GetProfilePictures.clear();
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
exit();
}
private void init() {
friendsList = (ListView) findViewById(R.id.friends_list);
friendsList.setOnItemClickListener(this);
friendsList.setAdapter(new FriendListAdapter(this));
friendsList.setTextFilterEnabled(true);
friendsList.setDivider(null);
friendsList.setDividerHeight(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.d(LOG_TAG, "onCreateOptionsMenu()");
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
/**
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(LOG_TAG, "onOptionsItemSelected()");
switch (item.getItemId()) {
case R.id.menu_refresh:
FacebookUtility.logout(this);
setProgressBarInDVisibility(true);
return true;
case R.id.retry_button:
GetProfilePictures.clear();
init();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
**/
public void onRequestReceived(int result, String message) {
Log.d(LOG_TAG, "onRequestReceived(" + result + ")");
if(isFinishing())
return;
// setProgressBarInDVisibility(false);
switch (result) {
case FacebookRequest.COMPLETED:
FacebookUtility.clearSession(this);
finish();
break;
case FacebookRequest.IO_EXCEPTION:
case FacebookRequest.FILE_NOT_FOUND_EXCEPTION:
case FacebookRequest.MALFORMED_URL_EXCEPTION:
case FacebookRequest.FACEBOOK_ERROR:
FacebookUtility.displayMessageBox(this, this.getString(R.string.logout_failed));
break;
}
}
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
// Log.d(LOG_TAG, "onItemClick()");
try {
final long friendId;
friendId = jsonArray.getJSONObject(position).getLong("uid");
String name = jsonArray.getJSONObject(position).getString("name");
new AlertDialog.Builder(this).setTitle(R.string.post_on_wall_title)
.setMessage(String.format(getString(R.string.post_on_wall), name))
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Bundle params = new Bundle();
params.putString("to", String.valueOf(friendId));
params.putString("caption", getString(R.string.app_name));
params.putString("description", getString(R.string.app_desc));
params.putString("picture", FacebookUtility.HACK_ICON_URL);
params.putString("name", getString(R.string.app_action));
FacebookUtility.facebook.dialog(FriendsList.this, "feed", params,
(DialogListener) new PostDialogListener());
}
}).setNegativeButton(R.string.no, null).show();
} catch (JSONException e) {
showToast("Error: " + e.getMessage());
}
}
public class PostDialogListener extends BaseDialogListener {
#Override
public void onComplete(Bundle values) {
final String postId = values.getString("post_id");
if (postId != null) {
showToast("Message posted on the wall.");
} else {
showToast("No message posted on the wall.");
}
}
}
public void showToast(final String msg) {
mHandler.post(new Runnable() {
#Override
public void run() {
Toast toast = Toast.makeText(FriendsList.this, msg, Toast.LENGTH_LONG);
toast.show();
}
});
}
public class FriendListAdapter extends BaseAdapter implements SectionIndexer {
private LayoutInflater mInflater;
private GetProfilePictures picturesGatherer = null;
FriendsList friendsList;
private String[] sections;
Hashtable<Integer, FriendItem> listofshit = null;
public FriendListAdapter(FriendsList friendsList) {
Log.d(LOG_TAG, "FriendListAdapter()");
this.friendsList = friendsList;
sections = new String[getCount()];
listofshit = new Hashtable<Integer, FriendItem>();
for (int i = 0; i < getCount(); i++) {
try {
sections[i] = jsonArray.getJSONObject(i).getString("name").substring(0);
sections[i] = jsonArray.getJSONObject(i).getString("birthday").substring(1);
} catch (JSONException e) {
sections[i] = "";
Log.e(LOG_TAG, "getJSONObject: " + e.getMessage());
}
}
if (picturesGatherer == null) {
picturesGatherer = new GetProfilePictures();
}
picturesGatherer.setAdapterForListener(this);
mInflater = LayoutInflater.from(friendsList.getBaseContext());
}
public int getCount() {
Log.d(LOG_TAG, "getCount()");
if (jsonArray == null)
return 0;
return jsonArray.length();
}
public Object getItem(int position) {
Log.d(LOG_TAG, "getItem()");
return listofshit.get(position);
}
public long getItemId(int position) {
Log.d(LOG_TAG, "getItemId()");
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
Log.d(LOG_TAG, "getView(" + position + ")");
JSONObject jsonObject = null;
try {
jsonObject = jsonArray.getJSONObject(position);
} catch (JSONException e) {
Log.e(LOG_TAG, "getJSONObject: " + e.getMessage());
}
FriendItem friendItem;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.single_friend, null);
friendItem = new FriendItem();
convertView.setTag(friendItem);
}
else {
friendItem = (FriendItem) convertView.getTag();
}
friendItem.friendPicture = (ImageView) convertView.findViewById(R.id.picture_square);
friendItem.friendName = (TextView) convertView.findViewById(R.id.name);
friendItem.friendDob = (TextView) convertView.findViewById(R.id.dob);
friendItem.friendLayout = (RelativeLayout) convertView.findViewById(R.id.friend_item);
try {
String uid = jsonObject.getString("uid");
String url = jsonObject.getString("pic_square");
friendItem.friendPicture.setImageBitmap(picturesGatherer.getPicture(uid, url));
} catch (JSONException e) {
Log.e(LOG_TAG, "getJSONObject: " + e.getMessage());
friendItem.friendName.setText("");
friendItem.friendDob.setText("");
}
try {
friendItem.friendName.setText(jsonObject.getString("name"));
friendItem.friendDob.setText(jsonObject.getString("birthday"));
} catch (JSONException e) {
Log.e(LOG_TAG, "getJSONObject: " + e.getMessage());
friendItem.friendName.setText("");
friendItem.friendDob.setText("");
}
listofshit.put(position, friendItem);
return convertView;
}
public int getPositionForSection(int position) {
return position;
}
public int getSectionForPosition(int position) {
return position;
}
public Object[] getSections() {
return sections;
}
}
class FriendItem {
TextView friendDob;
int id;
ImageView friendPicture;
TextView friendName;
RelativeLayout friendLayout;
}
}
TabSample.java:-
public class TabSample extends TabActivity {
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabmain);
setTabs() ;
}
private void setTabs()
{
addTab("All", R.drawable.tab_menu, FriendsList.class);
addTab("Current Month", R.drawable.tab_offers, FriendsList.class);
addTab("Current Week", R.drawable.tab_location, FriendsList.class);
addTab("Today", R.drawable.tab_reservation, FriendsList.class);
}
private void addTab(String labelId, int drawableId, Class<?> c)
{
TabHost tabHost = getTabHost();
Intent intent = new Intent(this, c);
TabHost.TabSpec spec = tabHost.newTabSpec("tab" + labelId);
View tabIndicator = LayoutInflater.from(this).inflate(R.layout.tab_indicator, getTabWidget(), false);
TextView title = (TextView) tabIndicator.findViewById(R.id.title);
title.setText(labelId);
ImageView icon = (ImageView) tabIndicator.findViewById(R.id.icon);
icon.setImageResource(drawableId);
spec.setIndicator(tabIndicator);
spec.setContent(intent);
tabHost.addTab(spec);
}
}
Please tell me where i have to add this code :
Bundle extras = getIntent().getExtras();
String response = extras.getString("FRIENDS");
Log.d(LOG_TAG, "onCreate()" + response);
try {
jsonArray = new JSONArray(response);
} catch (JSONException e) {
FacebookUtility.displayMessageBox(this, this.getString(R.string.json_failed));
}
and any other code need to move from FriendsList class to TabSample Class
I'm making an app that sends a notification to the status bar, it sends the notification when stepping through the code in the debugger, however it never sends the notification when run in realtime.
Here is my runnable that generates the notification, again when stepping through this code in the debugger the notification runs however in realtime nothing happens.
public class NewsEvents_Service extends Service {
private static final String NEWSEVENTS = "newsevents";
private static final String KEYWORDS = "keywords";
private NotificationManager mNM;
private ArrayList<NewsEvent> neList;
private int count;
#Override
public void onCreate() {
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
neList = new ArrayList<NewsEvent>();
getKeywords();
//getNewsEvents();
Thread thr = new Thread(null, mTask, "NewsEvents_Service");
thr.start();
Log.d("Thread", "IT STARTED!!!!!!????!!!!!!!!!!!!!!!?!!?");
}
#Override
public void onDestroy() {
// Cancel the notification -- we use the same ID that we had used to start it
mNM.cancel(R.string.ECS);
// Tell the user we stopped.
Toast.makeText(this, "Service Done", Toast.LENGTH_SHORT).show();
}
/**
* The function that runs in our worker thread
*/
Runnable mTask = new Runnable() {
public void run() {
getNewsEventsFromWeb();
for(NewsEvent ne : neList){
Log.d("Thread Running", "Service Code running!!!!!!!!!!!!!!!");
String body = ne.getBody().replaceAll("\\<.*?>", "");
String title = ne.getTitle();
for(String s : keyWordList){
if(body.contains(s) || body.contains(s.toLowerCase()) ||
title.contains(s) || title.contains(s.toLowerCase())){
ne.setInterested(true);
}
}
if(ne.isInterested() == true ){
Notification note = new Notification(R.drawable.icon,
"New ECS News Event", System.currentTimeMillis());
Intent i = new Intent(NewsEvents_Service.this, FullNewsEvent.class);
i.putExtra("ne", ne);
PendingIntent pi = PendingIntent.getActivity(NewsEvents_Service.this, 0,
i, 0);
note.setLatestEventInfo(NewsEvents_Service.this, "New Event", ne.getTitle(), pi);
note.flags = Notification.FLAG_AUTO_CANCEL;
mNM.notify(R.string.ECS, note);
}
}
}
};
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
/**
* Show a notification while this service is running.
*/
private void getNewsEventsFromWeb() {
HttpClient client = new DefaultHttpClient();
HttpGet get;
try {
get = new HttpGet(getString(R.string.jsonnewsevents));
ResponseHandler<String> response = new BasicResponseHandler();
String responseBody = client.execute(get, response);
String page = responseBody;
Bundle data = new Bundle();
data.putString("page",page);
Message msg = new Message();
msg.setData(data);
handler.sendMessage(msg);
}
catch (Throwable t) {
Log.d("UpdateNews", "PROBLEMS");
}
}
private Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
String page = msg.getData().getString("page");
try {
JSONArray parseArray = new JSONArray(page);
for (int i = 0; i < parseArray.length(); i++) {
JSONObject jo = parseArray.getJSONObject(i);
String title = jo.getString("title");
String body =jo.getString("body");
String pd = jo.getString("postDate");
String id = jo.getString("id");
NewsEvent ne = new NewsEvent(title, pd , body, id);
boolean unique = true;
for(NewsEvent ne0 : neList){
if(ne.getId().equals(ne0.getId())){
unique = false;
}else{
unique = true;
}
}
if(unique == true){
neList.add(ne);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
private ArrayList<String> keyWordList;
public void getNewsEvents(){
try {
InputStream fi = openFileInput(NEWSEVENTS);
if (fi!=null) {
ObjectInputStream in = new ObjectInputStream(fi);
neList = (ArrayList<NewsEvent>) in.readObject();
in.close();
}
}
catch (java.io.FileNotFoundException e) {
// that's OK, we probably haven't created it yet
}
catch (Throwable t) {
Toast
.makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
.show();
}
if(neList == null){
neList = new ArrayList<NewsEvent>();
}
}
public ArrayList<String> getKeywords(){
try {
InputStream fi = openFileInput(KEYWORDS);
if (fi!=null) {
ObjectInputStream in = new ObjectInputStream(fi);
keyWordList = (ArrayList<String>) in.readObject();
in.close();
}
}
catch (java.io.FileNotFoundException e) {
// that's OK, we probably haven't created it yet
}
catch (Throwable t) {
Toast
.makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
.show();
}
if(keyWordList == null){
keyWordList = new ArrayList<String>();
return keyWordList;
}
return keyWordList;
}
/**
* This is the object that receives interactions from clients. See RemoteService
* for a more complete example.
*/
private final IBinder mBinder = new Binder() {
#Override
protected boolean onTransact(int code, Parcel data, Parcel reply,
int flags) throws RemoteException {
return super.onTransact(code, data, reply, flags);
}
};
}
Here is my activity that schedules the service to run
public class NewsEvents extends ListActivity{
private URL JSONNewsEvents;
private ArrayList<NewsEvent> neList;
private ArrayList<String> keyWordList;
private Worker worker;
private NewsEvents ne;
public static final String KEYWORDS = "keywords";
private static final String NEWSEVENTS = "newsevents";
public static final int ONE_ID = Menu.FIRST+1;
private PendingIntent newsAlarm;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newsevents);
ne = this;
neList = new ArrayList<NewsEvent>();
try {
JSONNewsEvents = new URL(getString(R.string.jsonnewsevents));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
worker = new Worker(handler, this);
setListAdapter(new IconicAdapter());
getKeywords();
worker.execute(JSONNewsEvents);
}
#Override
protected void onStop() {
super.onStop();
writeNewsEvents() ;
}
#Override
protected void onPause(){
super.onPause();
writeNewsEvents();
}
private void writeNewsEvents() {
try {
OutputStream fi = openFileOutput(NEWSEVENTS, 0);
if (fi!=null) {
ObjectOutputStream out = new ObjectOutputStream(fi);
out.writeObject(neList);
out.close();
}
}
catch (java.io.FileNotFoundException e) {
// that's OK, we probably haven't created it yet
}
catch (Throwable t) {
Toast
.makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
.show();
}
}
/**
* #return
*/
public ArrayList<String> getKeywords(){
try {
InputStream fi = openFileInput(KEYWORDS);
if (fi!=null) {
ObjectInputStream in = new ObjectInputStream(fi);
keyWordList = (ArrayList<String>) in.readObject();
in.close();
}
}
catch (java.io.FileNotFoundException e) {
// that's OK, we probably haven't created it yet
}
catch (Throwable t) {
Toast
.makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
.show();
}
if(keyWordList == null){
keyWordList = new ArrayList<String>();
return keyWordList;
}
return keyWordList;
}
public void onListItemClick(ListView parent, View v,
int position, long id) {
startFullNewsEvent(neList.get(position));
}
/**
* #param newsEvent
*/
public void startFullNewsEvent(NewsEvent ne) {
Intent intent = new Intent(this, FullNewsEvent.class);
intent.putExtra("ne", ne);
this.startActivity(intent);
finish();
}
private Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
String page = msg.getData().getString("page");
try {
JSONArray parseArray = new JSONArray(page);
for (int i = 0; i < parseArray.length(); i++) {
JSONObject jo = parseArray.getJSONObject(i);
String title = jo.getString("title");
String body =jo.getString("body");
String pd = jo.getString("postDate");
String id = jo.getString("id");
NewsEvent ne = new NewsEvent(title, pd , body, id);
boolean unique = true;
for(NewsEvent ne0 : neList){
if(ne.getId().equals(ne0.getId())){
unique = false;
}else{
unique = true;
}
}
if(unique == true){
neList.add(ne);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ne.setListAdapter(new IconicAdapter());
}
};
public class IconicAdapter extends ArrayAdapter<NewsEvent> {
IconicAdapter() {
super(NewsEvents.this, R.layout.rownews, neList);
}
public View getView(int position, View convertView,ViewGroup parent) {
LayoutInflater inflater=getLayoutInflater();
View row=inflater.inflate(R.layout.rownews, parent, false);
TextView label=(TextView)row.findViewById(R.id.label);
ImageView image= (ImageView)row.findViewById(R.id.icon);
String body = neList.get(position).getBody();
body.replaceAll("\\<.*?>", "");
String title = neList.get(position).getTitle();
for(String s : keyWordList){
if(body.contains(s) || body.contains(s.toLowerCase()) ||
title.contains(s) || title.contains(s.toLowerCase())){
neList.get(position).setInterested(true);
}
}
if(neList.get(position).isInterested() == true){
image.setImageResource(R.drawable.star);
}
label.setText(neList.get(position).getTitle());
return(row);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
populateMenu(menu);
return(super.onCreateOptionsMenu(menu));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return(applyMenuChoice(item) || super.onOptionsItemSelected(item));
}
//Creates our activity to menus
private void populateMenu(Menu menu) {
menu.add(Menu.NONE, ONE_ID, Menu.NONE, "Home");
}
private boolean applyMenuChoice(MenuItem item) {
switch (item.getItemId()) {
case ONE_ID: startHome(); return(true);
}
return(false);
}
public void startHome() {
Intent intent = new Intent(this, ECS.class);
this.startActivity(intent);
finish();
}
}
Race conditions, I'm making an HTTP Request and then handing it off to a handler, immediately following that I iterator through the array list, which at full speed is empty because the HTTP hasn't completed. In debugging it all slows down so the HTTP is complete and all works well.
Threads and Network Connections, a deadly combination.