Monday 16 September 2013

Chat

First make xmpp package in that package create class name XmppClient

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.util.StringUtils;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

import com.easychat.app.ChatListAct;
import com.easychat.app.R;
import com.easychat.constant.Global;
import com.easychat.data.UserInfoChat;
import com.easychat.mlisteners.ChatReceiver;
import com.easychat.mlisteners.QueueChat;
import com.easychat.task.XMPPConn;
import com.easychat.utility.AroundLogger;
import com.easychat.utility.Utility;

public class XmppClient implements PacketListener{

private static final String TAG = "XmppClient";
static XMPPConnection connection;
static List<ChatReceiver> mChatReceivers;
static Context mContext;
private static XmppClient mXmppClient;
// static List<QueueChat> mQueueChats;
static HashMap<String, QueueChat> mQueueChats; 
static QueueChat mCurrentChatListener;
private XmppClient(Context context) {
mContext = context;
mQueueChats = new HashMap<String, QueueChat>();
}


public static XmppClient getInstance(Context context) {
if(mXmppClient == null) {
mXmppClient = new XmppClient(context);
}
return mXmppClient;
}


/*public void setCurrentChatListener(QueueChat queueChat) {
mCurrentChatListener = queueChat;
}*/

public static void setCurrentChatListener(String sender, ChatReceiver chatReceiver) {
mCurrentChatListener = new QueueChat();
mCurrentChatListener.setChatReceiver(chatReceiver);
mCurrentChatListener.setCount(0);
mCurrentChatListener.setSender(sender.toUpperCase());

removeChatFromQueue(sender.toUpperCase());
}

public static void removeCurrentChatListener() {
if(mCurrentChatListener != null) {
mCurrentChatListener = null;
}
}

public static void addChatInQueue(String sender, ChatReceiver chatReceiver) {
if(mQueueChats == null) mQueueChats = new HashMap<String, QueueChat>();
if(mQueueChats.size() > 0 && mQueueChats.containsKey(sender.toUpperCase())) {
QueueChat chat = mQueueChats.get(sender.toUpperCase());
int count = chat.increaseCounter();
QueueChat mQueueChat = new QueueChat();
mQueueChat.setChatReceiver(null);
mQueueChat.setCount(count);
mQueueChat.setSender(sender.toUpperCase());
mQueueChats.put(sender.toUpperCase(), mQueueChat);

// mQueueChats.put(sender.toUpperCase(), mQueueChats.get(sender.toUpperCase()).increaseCounter());
}else {
QueueChat mQueueChat = new QueueChat();
mQueueChat.setChatReceiver(null);
mQueueChat.setCount(1);
mQueueChat.setSender(sender.toUpperCase());
mQueueChats.put(sender.toUpperCase(), mQueueChat);
}
}

public static void removeChatFromQueue(String sender) {
if(mQueueChats != null) {
mQueueChats.remove(sender.toUpperCase());
}
}


public static int getChatQueueCount(String sender) {
if(mQueueChats != null && mQueueChats.containsKey(sender.toUpperCase())) {
return mQueueChats.get(sender.toUpperCase()).getCount();
}else {
return 0;
}
}

/*public static void addChatReceiver(ChatReceiver chatReceiver) {
if(mChatReceivers == null) {
mChatReceivers = new ArrayList<ChatReceiver>();
}

mChatReceivers.add(chatReceiver);
}*/

public static void removeChatReceiver(ChatReceiver chatReceiver) {
if(mChatReceivers != null && mChatReceivers.size()>0) {
mChatReceivers.remove(chatReceiver);
}
}

public static void setConnection(XMPPConnection xmppConnection, PacketListener packetListener) {
connection = xmppConnection;
if (connection != null) {
// Add a packet listener to get messages sent to us
PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
connection.addPacketListener(packetListener, filter);

/*filter = new MessageTypeFilter(Message.Type.fromString(Global.TYPE_INVITETOCHAT));
connection.addPacketListener(packetListener, filter);

filter = new MessageTypeFilter(Message.Type.fromString(Global.TYPE_INVITATION_ACCEPT));
connection.addPacketListener(packetListener, filter);

filter = new MessageTypeFilter(Message.Type.fromString(Global.TYPE_INVITATION_DECLINE));
connection.addPacketListener(packetListener, filter);*/

AroundLogger.info(TAG + "Registered for chat as " + connection.getUser());
}
}


public static void disconnect() {
if(connection != null && connection.isConnected()) {
if(mXmppClient != null) {
connection.removePacketListener(mXmppClient);
}
connection.disconnect();
}

}


@Override
public void processPacket(Packet packet) {
Message message = (Message) packet;

if (message.getBody() != null) {

if(message.getBody().equals(Global.TYPE_INVITETOADDFRIEND)) {
Intent  inivitetoAddFriend = new Intent(Global.ACTION_RECEIVED_INVITOADDFRIEND);

UserInfoChat userInfoChat = (UserInfoChat) message.getProperty("userinfo");
userInfoChat.sender= StringUtils.parseName(message.getFrom());
inivitetoAddFriend.putExtra("userinfo", userInfoChat);
mContext.sendBroadcast(inivitetoAddFriend);
}else if(message.getBody().equals(Global.TYPE_FRIEND_REQUEST_ACCEPT)) {
Intent invitationIntent = new Intent(Global.ACTION_RECEIVED_ACCEPT_FRIEND_REQUEST);
UserInfoChat userInfoChat = (UserInfoChat) message.getProperty("userinfo");
userInfoChat.sender = StringUtils.parseName(message.getFrom());
invitationIntent.putExtra("userinfo", userInfoChat);

mContext.sendBroadcast(invitationIntent);


}else if(message.getBody().equals(Global.TYPE_FRIEND_REQUEST_DECLINE)) {
Intent invitationIntent = new Intent(Global.ACTION_RECEIVED_DECLINE_FRIEND_REQUEST);
UserInfoChat userInfoChat = (UserInfoChat) message.getProperty("userinfo");
userInfoChat.sender = StringUtils.parseName(message.getFrom());
invitationIntent.putExtra("userinfo", userInfoChat);
mContext.sendBroadcast(invitationIntent);

}else if(message.getBody().equals(Global.TYPE_INVITETOCHAT)) {


Intent invitationIntent = new Intent(Global.ACTION_RECEIVED_INVITATIONTOCHAT);
UserInfoChat userInfoChat = (UserInfoChat) message.getProperty("userinfo");
userInfoChat.sender = StringUtils.parseName(message.getFrom());
invitationIntent.putExtra("userinfo", userInfoChat);
mContext.sendBroadcast(invitationIntent);

}else if(message.getBody().equals(Global.TYPE_INVITATION_ACCEPT)) {
Intent invitationIntent = new Intent(Global.ACTION_RECEIVED_ACCEPTCHATINVITATION);
UserInfoChat userInfoChat = (UserInfoChat) message.getProperty("userinfo");
userInfoChat.sender = StringUtils.parseName(message.getFrom());
invitationIntent.putExtra("userinfo", userInfoChat);

mContext.sendBroadcast(invitationIntent);


}else if(message.getBody().equals(Global.TYPE_INVITATION_DECLINE)) {
Intent invitationIntent = new Intent(Global.ACTION_RECEIVED_DECLINECHATINVITATION);
UserInfoChat userInfoChat = (UserInfoChat) message.getProperty("userinfo");
userInfoChat.sender = StringUtils.parseName(message.getFrom());
invitationIntent.putExtra("userinfo", userInfoChat);
mContext.sendBroadcast(invitationIntent);

}else if(message.getBody().equals(Global.TYPE_REQUEST_GALLERY)) {
Intent invitationIntent = new Intent(Global.ACTION_RECEIVED_GALLERY_REQUEST);
UserInfoChat userInfoChat = (UserInfoChat) message.getProperty("userinfo");
userInfoChat.sender = StringUtils.parseName(message.getFrom());
invitationIntent.putExtra("userinfo", userInfoChat);

mContext.sendBroadcast(invitationIntent);

}else if(message.getBody().equals(Global.TYPE_REQUEST_GALLERY_ACCEPT)) {
Intent invitationIntent = new Intent(Global.ACTION_RECEIVED_GALLERY_REQUEST_ACCCEPT);
UserInfoChat userInfoChat = (UserInfoChat) message.getProperty("userinfo");
userInfoChat.sender = StringUtils.parseName(message.getFrom());
invitationIntent.putExtra("userinfo", userInfoChat);

mContext.sendBroadcast(invitationIntent);


}else if(message.getBody().equals(Global.TYPE_REQUEST_GALLERY_DECLINE)) {
Intent invitationIntent = new Intent(Global.ACTION_RECEIVED_GALLERY_REQUEST_DECLINE);
UserInfoChat userInfoChat = (UserInfoChat) message.getProperty("userinfo");
userInfoChat.sender = StringUtils.parseName(message.getFrom());
invitationIntent.putExtra("userinfo", userInfoChat);

mContext.sendBroadcast(invitationIntent);

}else if(message.getBody().equals(Global.TYPE_NOTIFY_ONLINE)) {
Intent invitationIntent = new Intent(Global.ACTION_RECEIVED_NOTIFY_FRIEND_ONLINE);
invitationIntent.putExtra("sender", StringUtils.parseName(message.getFrom()));
mContext.sendBroadcast(invitationIntent);

}else {
// String fromName = StringUtils.parseBareAddress(message.getFrom());
AroundLogger.info(TAG + "Got text [" + message.getBody() + "] from [" + StringUtils.parseName(message.getFrom()) + "]");

if(mCurrentChatListener != null && mCurrentChatListener.getChatReceiver() != null && mCurrentChatListener.getSender().equalsIgnoreCase(StringUtils.parseName(message.getFrom()))) {
mCurrentChatListener.getChatReceiver().receive(message);

}else {
createNotification(message);
addChatInQueue(StringUtils.parseName(message.getFrom()), null);
}
}
}
}


public static boolean isConnected() {
if(connection != null && connection.isConnected()) {
return true;
}else {
return false;
}
}

private void createNotification(Message message) {
NotificationManager mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
int icon = R.drawable.app_icon;
CharSequence tickerText = mContext.getString(R.string.app_name);
long when = System.currentTimeMillis();

Notification notification = new Notification(icon, tickerText, when);
notification.flags |= Notification.FLAG_AUTO_CANCEL;

UserInfoChat mInfoChat = (UserInfoChat) message.getProperty("userinfo");

CharSequence contentTitle = StringUtils.parseName(message.getFrom());
CharSequence contentText = message.getBody();
Intent notificationIntent = new Intent(mContext, ChatListAct.class);
notificationIntent.putExtra("username", contentTitle.toString());
notificationIntent.putExtra("message", contentText);
notificationIntent.putExtra("userid", mInfoChat.userid);

// notificationIntent.putExtra("senderid", mInfoChat.senderId);
// notificationIntent.putExtra("status", (String)message.getProperty("status"));
PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);


notification.setLatestEventInfo(mContext, contentTitle, contentText, contentIntent);
mNotificationManager.notify(1, notification);
}

public static void sendMessage(final Context context, Message message) {

if(connection != null && connection.isConnected()) {
connection.sendPacket(message);
}else {
((Activity)context).runOnUiThread(new Runnable() {

@Override
public void run() {
Utility.showToast(context.getString(R.string.xmpp_disconnected_error), context);
new XMPPConn(context.getApplicationContext(), null).execute();
}
});
}
}




}


create next class name XmppConnectionListener

import org.jivesoftware.smack.ConnectionListener;

import android.content.Context;

import com.easychat.utility.AroundLogger;

public class XmppConnectionListener implements ConnectionListener{

static final String Tag = "XmppConnectionListener";
Context mContext;
public XmppConnectionListener(Context context) {
this.mContext = context;
}
@Override
public void connectionClosed() {

AroundLogger.info(Tag + " connectionClosed()");
// new XMPPConn(mContext, null).execute();
}

@Override
public void connectionClosedOnError(Exception arg0) {
// TODO Auto-generated method stub
AroundLogger.info(Tag + " connectionClosedOnError()");
}

@Override
public void reconnectingIn(int arg0) {
// TODO Auto-generated method stub
AroundLogger.info(Tag + " reconnectingIn()");
}

@Override
public void reconnectionFailed(Exception arg0) {
// TODO Auto-generated method stub
AroundLogger.info(Tag + " reconnectionFailed()");
}

@Override
public void reconnectionSuccessful() {
// TODO Auto-generated method stub
AroundLogger.info(Tag + " reconnectionSuccessful()");
}

}
create BroadcastReceiver class name ChatBroadcastReceiver

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import com.easychat.app.AddFriendInvitationDialogActivity;
import com.easychat.app.ChatInvitationDialogActivity;
import com.easychat.app.R;
import com.easychat.app.RequestGalleryImagesDialogActivity;
import com.easychat.app.SimpleDialogActivity;
import com.easychat.app.SimpleGalleryDialogActivity;
import com.easychat.constant.Global;
import com.easychat.data.UserInfoChat;
import com.easychat.utility.Utility;

public class ChatBroadcastReceiver extends BroadcastReceiver{

@Override
public void onReceive(Context context, Intent intent) {


if(intent.getAction().equals(Global.ACTION_RECEIVED_INVITOADDFRIEND)) {

Intent chatInvitationIntent = new Intent(context,AddFriendInvitationDialogActivity.class);

UserInfoChat mUserInfoChat =(UserInfoChat)intent.getSerializableExtra("userinfo");
chatInvitationIntent.putExtra("userinfo", mUserInfoChat);
chatInvitationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(chatInvitationIntent);
}else if(intent.getAction().equals(Global.ACTION_RECEIVED_ACCEPT_FRIEND_REQUEST)) {
Intent chatInvitationIntent = new Intent(context, SimpleDialogActivity.class);
UserInfoChat mUserInfoChat = (UserInfoChat) intent.getSerializableExtra("userinfo");
chatInvitationIntent.putExtra("userinfo", mUserInfoChat);
chatInvitationIntent.putExtra("accepted", true);
chatInvitationIntent.putExtra("flag", true);
chatInvitationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(chatInvitationIntent);

}else if(intent.getAction().equals(Global.ACTION_RECEIVED_DECLINE_FRIEND_REQUEST)) {
Intent chatInvitationIntent = new Intent(context, SimpleDialogActivity.class);
UserInfoChat mUserInfoChat = (UserInfoChat) intent.getSerializableExtra("userinfo");
chatInvitationIntent.putExtra("userinfo", mUserInfoChat);
chatInvitationIntent.putExtra("accepted", false);
chatInvitationIntent.putExtra("flag", true);
chatInvitationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(chatInvitationIntent);

}else if(intent.getAction().equals(Global.ACTION_RECEIVED_INVITATIONTOCHAT)) {
Intent chatInvitationIntent = new Intent(context, ChatInvitationDialogActivity.class);
UserInfoChat mUserInfoChat = (UserInfoChat) intent.getSerializableExtra("userinfo");
chatInvitationIntent.putExtra("userinfo", mUserInfoChat);
chatInvitationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(chatInvitationIntent);

}else if(intent.getAction().equals(Global.ACTION_RECEIVED_ACCEPTCHATINVITATION)) {
Intent chatInvitationIntent = new Intent(context, SimpleDialogActivity.class);
UserInfoChat mUserInfoChat = (UserInfoChat) intent.getSerializableExtra("userinfo");
chatInvitationIntent.putExtra("userinfo", mUserInfoChat);
chatInvitationIntent.putExtra("accepted", true);
chatInvitationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(chatInvitationIntent);

}else if(intent.getAction().equals(Global.ACTION_RECEIVED_DECLINECHATINVITATION)) {
Intent chatInvitationIntent = new Intent(context, SimpleDialogActivity.class);
UserInfoChat mUserInfoChat = (UserInfoChat) intent.getSerializableExtra("userinfo");
chatInvitationIntent.putExtra("userinfo", mUserInfoChat);

chatInvitationIntent.putExtra("accepted", false);
chatInvitationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(chatInvitationIntent);

}else if(intent.getAction().equals(Global.ACTION_RECEIVED_GALLERY_REQUEST)) {
Intent chatInvitationIntent = new Intent(context, RequestGalleryImagesDialogActivity.class);
UserInfoChat mUserInfoChat = (UserInfoChat) intent.getSerializableExtra("userinfo");
chatInvitationIntent.putExtra("userinfo", mUserInfoChat);

chatInvitationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(chatInvitationIntent);

}else if(intent.getAction().equals(Global.ACTION_RECEIVED_GALLERY_REQUEST_ACCCEPT)) {
Intent chatInvitationIntent = new Intent(context, SimpleGalleryDialogActivity.class);
UserInfoChat mUserInfoChat = (UserInfoChat) intent.getSerializableExtra("userinfo");
chatInvitationIntent.putExtra("userinfo", mUserInfoChat);

chatInvitationIntent.putExtra("accepted", true);
chatInvitationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(chatInvitationIntent);

}else if(intent.getAction().equals(Global.ACTION_RECEIVED_GALLERY_REQUEST_DECLINE)) {
Intent chatInvitationIntent = new Intent(context, SimpleGalleryDialogActivity.class);
UserInfoChat mUserInfoChat = (UserInfoChat) intent.getSerializableExtra("userinfo");
chatInvitationIntent.putExtra("userinfo", mUserInfoChat);

chatInvitationIntent.putExtra("accepted", false);
chatInvitationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(chatInvitationIntent);

}else if(intent.getAction().equals(Global.ACTION_RECEIVED_NOTIFY_FRIEND_ONLINE)) {
String notifyFriendsGetOnline = Utility.getSharedKey(Global.PREF_NOTIFY_FRIENDS_GET_ONLINE, context);
if(!TextUtils.isEmpty(notifyFriendsGetOnline) && Boolean.parseBoolean(notifyFriendsGetOnline)) {
String isStatusBarNotification = Utility.getSharedKey(Global.PREF_STATUSBAR_NOTIFICATION, context);

if(!TextUtils.isEmpty(isStatusBarNotification) && Boolean.parseBoolean(isStatusBarNotification)) {
//Create notification
createNotification(context, intent.getStringExtra("sender"));
}else {
//Display Toast
Utility.showToast(String.format(context.getString(R.string.xxx_user_is_online), intent.getStringExtra("sender")), context);
}
}
}
}

private void createNotification(Context mContext, String username) {
NotificationManager mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
int icon = R.drawable.app_icon;
CharSequence tickerText = mContext.getString(R.string.app_name);
long when = System.currentTimeMillis();

Notification notification = new Notification(icon, tickerText, when);
notification.flags |= Notification.FLAG_AUTO_CANCEL;

CharSequence contentText = String.format(mContext.getString(R.string.xxx_user_is_online), username);
Intent notificationIntent = new Intent();
PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);


notification.setLatestEventInfo(mContext, username, contentText, contentIntent);
mNotificationManager.notify(1, notification);
}
}



Thursday 12 September 2013

Interface

create class name MyInterface

public interface MyInterface {

public abstract  void Mydata(List<DataAll> listmy);
}

where you want list put below code

List<DataAll> Dataallobj;
BaseAdapter bas;

MyTask  task = new MyTask();
    task.setListeners(new MyInterface() {
    @Override
    public void Mydata(List<DataAll> listmy) {
    Dataallobj = listmy;
    mycontnamesetget = listmy;
    bas = new BaseAd(JitegaSlider.this);
    MyHandler.sendEmptyMessage(COMPLETEMAIN);
    }
    });

create class MyTask


public class MyTask  extends  AsyncTask<String,Void, List<DataAll>>
{
private static final String  TAG = "MyTask -";
List<DataAll> Dataallobj = new ArrayList<DataAll>();
MyInterface  objedatasend;
String Response;
boolean temp = true;
InputStream is = null;
 
@Override
protected List<DataAll> doInBackground(String... params) {
Log.i(General.TAG,TAG+"doInBackground -");
List<DataAll> Dataallobj = new ArrayList<DataAll>();
for (String url : params) 
{
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
Response = "";
try {
HttpResponse execute = client.execute(httpGet);

InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content),8);
String s = "";
while ((s = buffer.readLine()) != null) {
Response += s;
Log.i(General.TAG, "get response....."+Response);
}
} catch (Exception e) {
e.printStackTrace();
}
try {
JSONObject json = new JSONObject(Response.replaceAll("null", ""));
JSONObject jobj = json.getJSONObject("feed");
JSONArray jsonArray = jobj.getJSONArray("entry");
String Title = "";
String Vidio = "";
String Imageurl = "";
String Summary = "";
String ImgHeight = "";
String ImgWidth = "";
String Imgname = "";
String favouritecount = "";
String viewcount = "";
String numDislike = "0";
String numLike = "0";
String currentDateandTime = "";
String videotimedur = "";
String mytime = "";
JSONObject jobtitle = null,jobcontent=null,jobstatistic=null,jobjmedia = null,jobmediadesc=null,jobjrating=null,jobdate = null,jobvideotime = null;
if(jsonArray != null){
for (int i = 0; i < jsonArray.length(); i++) 
{
JSONObject Entryobj = jsonArray.getJSONObject(i);
// This Array For Getting ImageUrl                     
if(Entryobj.has("published")){
jobdate = Entryobj.getJSONObject("published");
}
if(Entryobj.has("title")){
jobtitle = Entryobj.getJSONObject("title");
}
if(Entryobj.has("yt$statistics")){
//null
jobstatistic = Entryobj.getJSONObject("yt$statistics");
}
if(Entryobj.has("media$group")){
jobjmedia = Entryobj.getJSONObject("media$group");
}
if(jobjmedia.has("media$description")){
jobmediadesc = jobjmedia.getJSONObject("media$description");
}
if(jobjmedia.has("yt$videoid")){
jobcontent = jobjmedia.getJSONObject("yt$videoid");
}
if(jobjmedia.has("yt$duration")){
jobvideotime = jobjmedia.getJSONObject("yt$duration");
}
if(Entryobj.has("yt$rating")){
//null
jobjrating = Entryobj.getJSONObject("yt$rating");
}
JSONArray MediaThumbnailArray = jobjmedia.getJSONArray("media$thumbnail");
for (int m = 0; m < MediaThumbnailArray.length(); m++) {
JSONObject MediaImg = MediaThumbnailArray.getJSONObject(m);
ImgHeight = MediaImg.getString("height");
if(ImgHeight.equalsIgnoreCase("360")){
Imageurl = MediaImg.getString("url");
}
ImgWidth = MediaImg.getString("width");
Imgname = MediaImg.getString("yt$name");
Log.i(TAG, "get image....."+Imageurl);
Log.i(TAG, "get ImgHeight....."+ImgHeight);
Log.i(TAG, "get ImgWidth....."+ImgWidth);
Log.i(TAG, "get Imgname....."+Imgname);
}
if(jobdate != null){
if(jobdate.has("$t")){
currentDateandTime = jobdate.getString("$t");
Log.i(TAG, "get currentDateandTime....."+currentDateandTime);
}
}
if(jobtitle != null){
if(jobtitle.has("$t")){
Title = jobtitle.getString("$t");
Log.i(General.TAG, "get title...."+Title);
}
}
if(jobmediadesc != null){
if(jobmediadesc.has("$t")){
Summary = jobmediadesc.getString("$t");
Log.i(General.TAG, "get Summary...."+Summary);
}
}
if(jobcontent != null){
if(jobcontent.has("$t")){
Vidio =  jobcontent.getString("$t");
Log.i(General.TAG, "get Vidio url...."+Vidio);
}
}
if(jobvideotime != null){
if(jobvideotime.has("seconds")){
videotimedur =  jobvideotime.getString("seconds");
Log.i(General.TAG, "get Vidio time in seconds...."+Vidio);
 mytime = getDurationString(Integer.parseInt(videotimedur));
        Log.i(TAG, "get mytime..."+mytime);
}
}
if(jobstatistic != null){
if(jobstatistic.has("favoriteCount")){
favouritecount = jobstatistic.getString("favoriteCount");
Log.i(General.TAG, "get favouritecount...."+favouritecount);
}
if(jobstatistic.has("viewCount")){
viewcount = jobstatistic.getString("viewCount");
Log.i(General.TAG, "get viewcount...."+viewcount);
}
}
if(jobjrating != null){
if(jobjrating.has("numDislikes")){
numDislike = jobjrating.getString("numDislikes");
Log.i(General.TAG, "get numDislike...."+numDislike);
}
if(jobjrating.has("numLikes")){
numLike = jobjrating.getString("numLikes");
Log.i(General.TAG, "get numLike...."+numLike);
}
}
Dataallobj.add(new DataAll(Title,Summary,Vidio,Imageurl,ImgHeight,ImgWidth,Imgname,favouritecount,viewcount,numDislike,numLike,currentDateandTime,mytime));
}}
} catch (Exception e) {
System.out.println("" + e.toString());
Log.i(General.TAG,TAG +" To Parse Json Data On BackGroundMehtod Errore");
}
}
return Dataallobj;
}

@Override
protected void onPostExecute(List<DataAll> result) {
Log.i(General.TAG,TAG+"onPostExecute - Result: "+result);
super.onPostExecute(result);  
objedatasend.Mydata(result);
 
}


public void setListeners(MyInterface  datasend)
{
 Log.i(General.TAG,TAG+" setListeners -");
 objedatasend = datasend;  
}


private String getDurationString(int seconds) {

    int hours = seconds / 3600;
    int minutes = (seconds % 3600) / 60;
    seconds = seconds % 60;

    return twoDigitString(hours) + " : " + twoDigitString(minutes) + " : " + twoDigitString(seconds);
}

private String twoDigitString(int number) {

    if (number == 0) {
        return "00";
    }

    if (number / 10 == 0) {
        return "0" + number;
    }

    return String.valueOf(number);
}

}

Wednesday 11 September 2013

Android Set Multiple Alarms

// context variable contains your `Context`
AlarmManager mgrAlarm = (AlarmManager) context.getSystemService(ALARM_SERVICE);
ArrayList<PendingIntent> intentArray = new ArrayList<PendingIntent>();

for(i = 0; i < 10; ++i)
{
   Intent intent = new Intent(context, OnAlarmReceiver.class);
   // Loop counter `i` is used as a `requestCode`
   PendingIntent pendingIntent = PendingIntent.getBroadcast(context, i, intent, 0);
   // Single alarms in 1, 2, ..., 10 minutes (in `i` minutes)
   mgrAlarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 
                SystemClock.elapsedRealtime() + 60000 * i, 
                pendingIntent); 

   intentArray.add(pendingIntent);
}
 
Then if you need to cancel them:
 
 
private void cancelAlarms(){
    if(intentArray.size()>0){
        for(int i=0; i<intentArray.size(); i++){
            alarmmanager.cancel(intentArray.get(i));
        }
        intentArray.clear();
    }
} 

Monday 26 August 2013

Create menu in dialog

main.xml layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical|center_horizontal"
        android:text="@string/hello"
        android:textSize="30sp"
        />
</LinearLayout>





put below strings in strings.xml layout


<string name="hello">Hello, Press Menu button!</string>
        <string name="app_name">MenuDialogDemo</string>

        <string name="menu_line_1">Menu Line 1</string>
        <string name="menu_line_2">Click To Enter SubMenu</string>
        <string name="menu_line_3">Menu Line 3</string>
        <string name="menu_line_4">Menu Line 4</string>
        <string name="menu_line_5">Menu Line 5</string>

        <string name="menu_line_6">Menu Line 6</string>
        <string name="menu_line_7">Menu Line 7</string>
        <string name="menu_line_8">Menu Line 8</string>
        <string name="menu_line_9">Menu Line 9</string>
        <string name="menu_line_a">Menu Line A</string>

        <string name="sub_menu_line_1">SubMenu Line 1</string>
        <string name="sub_menu_line_2">SubMenu Line 2</string>
        <string name="sub_menu_line_3">SubMenu Line 3</string>





MainActivity.java code

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.Toast;

/**
 * Demo illustrating how to use MenuDialg
 */
public class
MainActivity extends Activity
    implements MenuDialog.MenuSelectListener
{
    // main menu:
    static final MenuDialog.MenuItem[] MAIN_MENU_LIST = {
        new MenuDialog.MenuItem(android.R.drawable.ic_dialog_email, R.string.menu_line_1),
        new MenuDialog.MenuItem(android.R.drawable.btn_plus, R.string.menu_line_2),
        new MenuDialog.MenuItem(android.R.drawable.ic_menu_directions, R.string.menu_line_3),
        new MenuDialog.MenuItem(android.R.drawable.ic_menu_compass, R.string.menu_line_4),
        new MenuDialog.MenuItem(android.R.drawable.btn_star, 0),                                // only icon, no text
        new MenuDialog.MenuItem(android.R.drawable.ic_dialog_info, R.string.menu_line_6),
        new MenuDialog.MenuItem(android.R.drawable.ic_media_next, R.string.menu_line_7),
        new MenuDialog.MenuItem(android.R.drawable.ic_input_delete, R.string.menu_line_8),
        new MenuDialog.MenuItem(android.R.drawable.ic_lock_lock, R.string.menu_line_9),
        new MenuDialog.MenuItem(android.R.drawable.ic_media_pause, R.string.menu_line_a)
    };
    // submenu:
    static final MenuDialog.MenuItem[] SUBMENU_LIST = {
        new MenuDialog.MenuItem(android.R.drawable.btn_minus, R.string.sub_menu_line_1),
        new MenuDialog.MenuItem(android.R.drawable.btn_minus, R.string.sub_menu_line_2),
    };

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    /** must be implemented to intercept menu key */
    @Override
    public boolean onKeyUp( int keyCode, KeyEvent event ) {
        if (keyCode == KeyEvent.KEYCODE_MENU) {
            // intercept menu key
            new MenuDialog( this, this, MAIN_MENU_LIST, R.drawable.logo1 );    // launch main menu
            return true;
        }
        return super.onKeyDown( keyCode, event );
    }
    /**
     * MenuDialog.MenuSelectListener implementation, gets invoked when the user selects a menu item
     * to access submenu construct MenuDialog as a response
     */
    @Override
    public void onMenuSelect( int index, long id ) {
        Toast.makeText( this, "selected item " + index + ", id=" + id, Toast.LENGTH_SHORT ).show();
        if( id == R.string.menu_line_2 ) {
            new MenuDialog( this, this, SUBMENU_LIST, R.drawable.android );    // launch submenu
        }
    }
}


create class name MenuDialog.java

import android.app.Dialog;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;

/**
 * MenuDialog - displays the menu in a more traditional way
 */
public class MenuDialog extends Dialog {
    static final int
        MARGIN_X                    = 10,
        MARGIN_Y                    = 0,
        dummy_int = 0;

    static final float
        LINE_TEXT_SIZE                = 30.0F,
        dummy_float = 0;
   
    Drawable mLogo;
    ListView mListView;

    /**
     * Constructs and shows menu
     * @param context - calling context
     * @param menuSelectListener - callback interface
     * @param menuList - list of menu items
     * @param logoRes - image resource id or 0
     */
    public MenuDialog( final Context context, final MenuSelectListener menuSelectListener, final MenuItem[] menuList, int logoRes ) {
        super( context );

        if( menuSelectListener == null || menuList == null ) {
            return;    // exception?
       }

        final Resources resources = context.getResources();
        mLogo = new BitmapDrawable( BitmapFactory.decodeResource(resources, logoRes) );
        requestWindowFeature( Window.FEATURE_NO_TITLE );
        setContentView( createMenuLayout(context) );

        BaseAdapter adapter = new BaseAdapter() {
            @Override
            public int getCount() {
                return menuList.length;
            }
            @Override
            /* * */
            public Object getItem( int position ) {
                return position;
            }
            /* * */
            @Override
            public long getItemId( int position ) {
                int id = menuList[position].mTextResourceId;
                if( id == 0 ) id = menuList[position].mIconResourceId;
                return id;
            }
            /* * */
            @Override
            public View getView( int position, View convertView, ViewGroup parent ) {
                if( convertView == null ) {
                    convertView = new TextView( context );
                }

                TextView textView = (TextView)convertView;
                if( position < menuList.length ) {
                    if( menuList[position].mTextResourceId == 0 ) {
                        textView.setText( null );
                    } else {
                        textView.setText( resources.getString(menuList[position].mTextResourceId) );
                    }
                    textView.setTextSize( LINE_TEXT_SIZE );
                    textView.setTextColor( Color.WHITE );

                    if( menuList[position].mIconResourceId == 0 ) {
                        textView.setCompoundDrawablesWithIntrinsicBounds( 0, 0, 0, 0 );
                    } else {
                        textView.setCompoundDrawablesWithIntrinsicBounds( menuList[position].mIconResourceId, 0, 0, 0 );
                    }
                }
                return convertView;
            }
        };

        mListView.setAdapter( adapter );
        mListView.setOnItemClickListener( new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int clicked, long id ) {
                menuSelectListener.onMenuSelect( clicked, id );
                MenuDialog.this.dismiss();
            }
        });

        super.show();
    }

    View createMenuLayout( Context context) {
        LinearLayout linearLayout = new LinearLayout( context );

        linearLayout.setOrientation( LinearLayout.HORIZONTAL );
        linearLayout.setMinimumHeight( android.view.ViewGroup.LayoutParams.WRAP_CONTENT );
        linearLayout.setMinimumWidth( android.view.ViewGroup.LayoutParams.FILL_PARENT );

        if( mLogo != null ) {
            ImageView imageView = new ImageView( context );
            imageView.setLayoutParams( new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) );
            imageView.setImageDrawable( mLogo );

            linearLayout.addView( imageView );
        }

        mListView = new ListView( context );
        mListView.setLayoutParams( new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) );
        mListView.setPadding( MARGIN_X, MARGIN_Y, 0, 0 );
        mListView.setBackgroundColor( Color.DKGRAY );
        linearLayout.addView( mListView );

        return linearLayout;
    }
    /**
     * Menu item - used in MenuDialog constructor
     * contains
     *     mIconResourceId or 0
     *     mTextResourceId or 0
     * expected that at least one of these will be not 0
     * the program will crash if non-zero resource id is invalid
     */
    public static class MenuItem {
        int mIconResourceId;
        int mTextResourceId;

        /**
         * MenuDialog.MenuItem constructor.
         * @param iconResourceId - valid icon resource id or 0
         * @param textResourceId - valid text resource id or 0
         * at least one of these must be non-zero
         */
        public MenuItem( int iconResourceId, int textResourceId ) {
            this.mIconResourceId = iconResourceId;
            this.mTextResourceId = textResourceId;
        }
    }
    /**
     * Menu selection listener - used in MenuDialog constructor
     */
    public static interface MenuSelectListener {
        /**
         * Gets invoked when a user selects a menu item
         * @param index - selected index in MenuItem[]
         * @param id - selected text resource id or icon resource id (if textResourceId == 0) in MenuItem[]
         */
        public void onMenuSelect( int index, long id );
    }
}

Find Hours Diffrence in Kotlin

  In Kotlin, determining the difference in hours between two timestamps is a common task, especially in scenarios involving time-based calcu...