Display RTP stream using GstSharp - gstreamer

I want to read a RTP stream and display it in WPF. I have the basic example working with RTSP, but I can't make it work with basic RTP. I believe I have problems with caps settings, but I'm not sure how or why.
There is the input stream encoded with gst-launch:
gst-launch-1.0 dx9screencapsrc width=1920 height=1080 monitor=1 ! "video/x-raw, framerate=30/1" ! videoconvert ! x264enc speed-preset=ultrafast threads=4 sliced-threads=true ! rtph264pay config-interval=1 pt=96 ! udpsink host=127.0.0.1 port = 5600
I have successfully decoded the stream using:
gst-launch-1.0 udpsrc port=5600 ! "application/x-rtp" ! rtph264depay ! avdec_h264 max-threads=12 ! autovideosink
I am therefore trying to use the same pipeline with gstSharp. Here is what I have so far:
using System;
using System.Linq;
using GLib;
using Gst;
using Gst.Video;
using Thread = System.Threading.Thread;
namespace GStreamerD3D.Samples.WPF.D3D11
{
public class Playback
{
private static readonly log4net.ILog _log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public delegate void OnDrawReceivedEventHandler(Element videoSink, GLib.SignalArgs args);
private Pipeline _pipeline;
private MainLoop _mainLoop;
private Thread _mainGlibThread;
private Element _uriDecodeBin, _depay, _avdec, _audioConvert, _videoConvert;
private Element _audioSink, _videoSink;
private VideoOverlayAdapter _adapter;
private IntPtr _handle;
private const bool _enableAudio = false;
private const string _videoDecoder = "d3d11h264dec"; // This decoder will reduce CPU usage significantly
private bool _enableOverlay;
private string _source = "rtsp://localhost:8554/";
public Playback(IntPtr hwnd, bool enableOverlay, string gstDebug = "")
{
_handle = hwnd;
_enableOverlay = enableOverlay;
if (!String.IsNullOrEmpty(gstDebug))
{
Environment.SetEnvironmentVariable("GST_DEBUG", gstDebug);
}
InitGst();
CreatePipeline();
var ret = _pipeline.SetState(State.Playing);
if (ret == StateChangeReturn.Failure)
{
Log("Unable to set the pipeline to the playing state.", LogLevelFlags.Error);
return;
}
}
public OnDrawReceivedEventHandler OnDrawSignalReceived;
public void InitGst()
{
Gst.Application.Init();
GtkSharp.GstreamerSharp.ObjectManager.Initialize();
_mainLoop = new MainLoop();
_mainGlibThread = new Thread(_mainLoop.Run);
_mainGlibThread.Start();
}
private void CreatePipeline()
{
Log("Initializing Pipeline..", LogLevelFlags.Debug);
_pipeline = new Pipeline("pipeline0");
_pipeline.Bus.EnableSyncMessageEmission();
_pipeline.Bus.AddSignalWatch();
_pipeline.Bus.Message += OnBusMessage;
_pipeline.AutoFlushBus = true;
if (!_enableOverlay)
{
_pipeline.Bus.SyncMessage += OnBusSyncMessage;
}
CreateElements();
_pipeline.Add(_uriDecodeBin, _depay, _avdec, _videoConvert, _videoSink);
if (!_videoConvert.Link(_videoSink))
{
Log("Video sink could not be linked", LogLevelFlags.FlagFatal);
return;
}
}
private void OnBusSyncMessage(object o, SyncMessageArgs sargs)
{
Message msg = sargs.Message;
if (!Gst.Video.Global.IsVideoOverlayPrepareWindowHandleMessage(msg))
{
msg.Dispose();
return;
}
Element src = msg.Src as Element;
if (src == null)
{
msg.Dispose();
return;
}
try
{
src["force-aspect-ratio"] = true;
}
catch (PropertyNotFoundException ex)
{
Console.WriteLine(ex.Message, ex);
}
Element overlay = (_pipeline)?.GetByInterface(VideoOverlayAdapter.GType);
_adapter = new VideoOverlayAdapter(overlay.Handle);
_adapter.WindowHandle = _handle;
_adapter.HandleEvents(true);
msg?.Dispose();
overlay?.Dispose();
src?.Dispose();
}
protected bool CreateElements()
{
try
{
_videoSink = ElementFactory.Make("d3d11videosink", "d3d11videosink0");
if (_enableOverlay)
{
_videoSink["draw-on-shared-texture"] = true;
_videoSink.Connect("begin-draw", VideoSink_OnBeginDraw);
}
//SetPrimaryDecoder(_videoDecoder);
_videoConvert = ElementFactory.Make("videoconvert", "videoconvert0");
if (_videoSink == null)
{
Log($"Could not locate Direct3D11", LogLevelFlags.Error);
_videoSink = ElementFactory.Make("autovideosink", "autovideosink0");
}
_uriDecodeBin = ElementFactory.Make("udpsrc", "source");
_uriDecodeBin["port"] = 5600;
var caps = Gst.Global.CapsFromString("application/x-rtp, payload=(int)96");
_uriDecodeBin["caps"] = caps;
_depay = ElementFactory.Make("rtph264depay", "depay");
Log($"Linking rtspsrc: {_uriDecodeBin.Link(_depay)}", LogLevelFlags.Message);
_avdec = ElementFactory.Make("avdec_h264", "avdec");
//_uriDecodeBin.PadAdded += OnPadAdded;
}
catch (Exception ex)
{
Log(ex.ToString(), LogLevelFlags.Critical, ex);
return false;
}
return true;
}
private void OnBusMessage(object o, MessageArgs margs)
{
try
{
Message message = margs.Message;
switch (message.Type)
{
case MessageType.Eos:
Log("Replaying stream...", LogLevelFlags.Info);
var ret = _pipeline.SetState(Gst.State.Ready);
if (ret == StateChangeReturn.Async)
ret = _pipeline.GetState(out var state, out var pending, Gst.Constants.SECOND * 10L);
if (ret == StateChangeReturn.Success)
{
ret = _pipeline.SetState(Gst.State.Playing);
if (ret == StateChangeReturn.Async)
ret = _pipeline.GetState(out var state, out var pending, Gst.Constants.SECOND * 10L);
}
break;
case MessageType.Error:
message.ParseError(out GException err, out string debug);
if (debug == null)
{
debug = "none";
}
Log($"Error! Bus message: {debug}", LogLevelFlags.Error, err);
if (err.Code == 3)
{
System.Windows.Application.Current.Dispatcher.InvokeShutdown();
}
break;
}
}
catch (Exception ex)
{
Log("Bus message error.", LogLevelFlags.Error, ex);
}
}
private void VideoSink_OnBeginDraw(object o, GLib.SignalArgs args)
{
OnDrawSignalReceived?.Invoke((Element)o, args);
}
public void Log(string message, LogLevelFlags logLevel, Exception exception = null)
{
try
{
switch (logLevel)
{
case LogLevelFlags.Debug:
_log.Debug(message, exception);
break;
case LogLevelFlags.Info:
_log.Info(message, exception);
break;
case LogLevelFlags.Warning:
_log.Warn(message, exception);
break;
case LogLevelFlags.Error:
_log.Error(message, exception);
break;
case LogLevelFlags.FlagFatal:
_log.Fatal(message, exception);
break;
default:
_log.Info(message, exception);
break;
}
}
catch (Exception ex)
{
_log.Error($"Log error: {ex.Message}", ex);
}
}
internal void Cleanup()
{
try
{
Log("Cleaning up pipeline..", LogLevelFlags.Info);
_adapter?.HandleEvents(false);
_videoSink?.Disconnect("begin-draw", VideoSink_OnBeginDraw);
if (_pipeline != null)
{
_pipeline.Bus.Message -= OnBusMessage;
_pipeline.Bus.SyncMessage -= OnBusSyncMessage;
}
_pipeline?.SetState(State.Null);
_pipeline?.Dispose();
_mainLoop?.Quit();
GC.Collect();
GC.WaitForPendingFinalizers();
}
catch (Exception ex)
{
Log("Failed to cleanup resources", LogLevelFlags.Error, ex);
}
}
}
}
The most relevant part is extracted below:
protected bool CreateElements()
{
try
{
_videoSink = ElementFactory.Make("d3d11videosink", "d3d11videosink0");
if (_enableOverlay)
{
_videoSink["draw-on-shared-texture"] = true;
_videoSink.Connect("begin-draw", VideoSink_OnBeginDraw);
}
//SetPrimaryDecoder(_videoDecoder);
_videoConvert = ElementFactory.Make("videoconvert", "videoconvert0");
if (_videoSink == null)
{
Log($"Could not locate Direct3D11", LogLevelFlags.Error);
_videoSink = ElementFactory.Make("autovideosink", "autovideosink0");
}
_uriDecodeBin = ElementFactory.Make("udpsrc", "source");
_uriDecodeBin["port"] = 5600;
var caps = Gst.Global.CapsFromString("application/x-rtp, payload=(int)96");
_uriDecodeBin["caps"] = caps;
_depay = ElementFactory.Make("rtph264depay", "depay");
Log($"Linking rtspsrc: {_uriDecodeBin.Link(_depay)}", LogLevelFlags.Message);
_avdec = ElementFactory.Make("avdec_h264", "avdec");
//_uriDecodeBin.PadAdded += OnPadAdded;
}
catch (Exception ex)
{
Log(ex.ToString(), LogLevelFlags.Critical, ex);
return false;
}
return true;
}
This code sends an error
../libs/gst/base/gstbasesrc.c(3127): gst_base_src_loop (): /GstPipeline:pipeline0/GstUDPSrc:source:
streaming stopped, reason not-linked (-1)

I've finally found the answer after hours of research. I will post it in case somebody finds himself in the same situation:
the different elements need to be manually linked. The link must be AFTER the elements are added to the pipeline. In rtsp, the linking is made dynamically after the source pad is added.
private void CreatePipeline()
{
Log("Initializing Pipeline..", LogLevelFlags.Debug);
_pipeline = new Pipeline("pipeline0");
_pipeline.Bus.EnableSyncMessageEmission();
_pipeline.Bus.AddSignalWatch();
_pipeline.Bus.Message += OnBusMessage;
_pipeline.AutoFlushBus = true;
if (!_enableOverlay)
{
_pipeline.Bus.SyncMessage += OnBusSyncMessage;
}
CreateElements();
if (_enableAudio)
{
_pipeline.Add(_uriDecodeBin, _audioConvert, _videoConvert, _audioSink, _videoSink);
if (!_audioConvert.Link(_audioSink))
{
Log("Audio sink could not be linked", LogLevelFlags.Error);
return;
}
}
else
{
_pipeline.Add(_uriDecodeBin, _depay, _avdec, _videoConvert, _videoSink);
}
#### added here ####
_uriDecodeBin.Link(_depay);
_depay.Link(_avdec);
_avdec.Link(_videoConvert);
_videoConvert.Link(_videoSink);
####################
}

Related

ionic 2 cordova-plugin-media buffers mp3 files before streaming

I am new to cordova-media-plugin, I am using it in Ionic 2 App to stream mp3 files from the internet. But I noticed, files are not being streamed directly, they are downloaded locally first, then playing starts.
I follow the below tutorial in Ionic Native documentation:
https://ionicframework.com/docs/native/media/
Below is the code which I am using to create the MediaObject:
export class CLesson{
name: string;
id: number;
order: number;
url: string;
isPlaying: boolean = false;
audioFile: MediaObject = null;
listeningSeries: LessonStateChangeListener = null;
constructor(beCLesson : BeCLesson, listeningSeries : LessonStateChangeListener = null)
{
this.name = beCLesson.name;
this.id = beCLesson.id;
this.order = beCLesson.order;
this.url = beCLesson.url;
if(listeningSeries != null)
this.listeningSeries = listeningSeries;
}
initAudioFile(mediaPlugin : MediaPlugin)
{
const onStatusUpdate = (status) => console.log(status);
const onSuccess = () => console.log('Action is successful.');
const onError = (error) => console.error(error.message);
if(this.audioFile == null)
this.audioFile = mediaPlugin.create(this.url, onStatusUpdate, onSuccess, onError);
}
play()
{
// Notify the series that this lesson started playing
if(this.listeningSeries != null)
this.listeningSeries.onPlayStateChange(this);
if(this.audioFile != null)
{
this.audioFile.play();
this.isPlaying = true;
}
}
pause()
{
// Notify the series that this lesson paused playing
if(this.listeningSeries != null)
this.listeningSeries.onPauseStateChange(this);
if(this.audioFile != null)
{
this.audioFile.pause();
this.isPlaying = false;
}
}
stop()
{
// Notify the series that this lesson paused playing
if(this.listeningSeries != null)
this.listeningSeries.onStopStateChange(this);
if(this.audioFile != null)
{
this.audioFile.stop();
this.isPlaying = false;
}
}
}
Is this issue normal? ... how can I stream mp3 files from the internet without downloading them locally?
Thanks,

On using swipe refresh in recyclerview my adapter is not getting data when it is refreshing

My Latest fragment
public class Latest extends Fragment {
private RecyclerView recyclerLatest;
private SwipeRefreshLayout swipeRecycler;
private RecyclerView.LayoutManager mLayoutManager;
private List<LatestAdDetails> latestAdDetailsList = new ArrayList<>();
private LatestAdapter latestAdapter;
private LatestAdDetails latestAdDetails,latestAdDetails1;
private JSONObject jsonobject;
private Context context;
private String x;
public Latest() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View mainView=inflater.inflate(R.layout.latest_fragment,container,false);
recyclerLatest = (RecyclerView) mainView.findViewById(R.id.recycler_latest);
swipeRecycler= (SwipeRefreshLayout)mainView.findViewById(R.id.swipe_recycler_latest);
mLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
recyclerLatest.setLayoutManager(mLayoutManager);
recyclerLatest.setHasFixedSize(true);
context = getContext();
// url for latest add obtaining
UrlConstants.latest_ad_obtained= UrlConstants.latest_ad+ AppController.getString(getActivity().getApplicationContext(),"country_id")+"/"+AppController.getString(getActivity().getApplicationContext(),"city_id");
latestAdapter = new LatestAdapter(latestAdDetailsList);
recyclerLatest.setAdapter(latestAdapter);
latestAdd();
swipeRecycler.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh(){refreshLatestAd();
}
});
return mainView;
}
private void refreshLatestAd() {
UrlConstants.latset_ad_refresh_obtained=UrlConstants.latest_ad_refresh+
AppController.getString(getActivity().getApplicationContext(),"country_id")+"/"+
AppController.getString(getActivity().getApplicationContext(),"city_id")+"/"+
AppController.getString(getActivity().getApplicationContext(),"refresh_ad")+"/"+0;
LatestRefreshHandler latestRefreshHandler = new LatestRefreshHandler("latestRefreshADD");
latestRefreshHandler.executeAsStringRequest(new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("response", response);
JSONArray jsonarray = null;
try {
jsonarray = new JSONArray(response);
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < jsonarray.length(); i++) {
try {
jsonobject = jsonarray.getJSONObject(i);
if (jsonobject.getString("default_photo").isEmpty()) {
x = UrlConstants.default_photo;
} else {
x = jsonobject.getString("default_photo");
}
Log.e("x", x);
latestAdapter.clear();
int Ad_id_refresh = jsonarray.getJSONObject(jsonarray.length()).getInt("id");
AppController.setString(context,"refresh_ad", String.valueOf(Ad_id_refresh));
latestAdDetails = new LatestAdDetails(
jsonobject.getInt("id"),
jsonobject.getInt("cityid"),
jsonobject.getInt("price"),
jsonobject.getInt("type"),
jsonobject.getInt("comments"),
jsonobject.getInt("categoryid"),
jsonobject.getInt("MainCategoryID"),
jsonobject.getInt("created"),
jsonobject.getInt("views"),
jsonobject.getString("title"),
jsonobject.getString("default_photo"),
jsonobject.getString("CityName"),
jsonobject.getString("CategoryName"),
jsonobject.getString("storeid"),
jsonobject.getString("currency"),
jsonobject.getString("description"),
jsonobject.getDouble("Latitude"),
jsonobject.getDouble("Longitude")
);
latestAdDetailsList.add(latestAdDetails);
} catch (JSONException e) {
e.printStackTrace();
}
}
latestAdapter.addAll(latestAdDetailsList);
latestAdapter.notifyDataSetChanged();
recyclerLatest.setAdapter(latestAdapter);
swipeRecycler.setRefreshing(false);
}
}, new BaseRequest.ErrorResponseCallback() {
#Override
public void onError(Exception exception) {
}
});
}
private void latestAdd() {
LatestRequestHandler latestHandler = new LatestRequestHandler("latestADD");
latestHandler.executeAsStringRequest(new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("response", response);
JSONArray jsonarray = null;
try {
jsonarray = new JSONArray(response);
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < jsonarray.length(); i++) {
try {
jsonobject = jsonarray.getJSONObject(i);
if (jsonobject.getString("default_photo").isEmpty()) {
x = UrlConstants.default_photo;
} else {
x = jsonobject.getString("default_photo");
}
Log.e("x", x);
int Ad_id_refresh = jsonarray.getJSONObject(1).getInt("id");
AppController.setString(context,"refresh_ad", String.valueOf(Ad_id_refresh));
latestAdDetails = new LatestAdDetails(
jsonobject.getInt("id"),
jsonobject.getInt("cityid"),
jsonobject.getInt("price"),
jsonobject.getInt("type"),
jsonobject.getInt("comments"),
jsonobject.getInt("categoryid"),
jsonobject.getInt("MainCategoryID"),
jsonobject.getInt("created"),
jsonobject.getInt("views"),
jsonobject.getString("title"),
jsonobject.getString("default_photo"),
jsonobject.getString("CityName"),
jsonobject.getString("CategoryName"),
jsonobject.getString("storeid"),
jsonobject.getString("currency"),
jsonobject.getString("description"),
jsonobject.getDouble("Latitude"),
jsonobject.getDouble("Longitude")
);
latestAdDetailsList.add(latestAdDetails);
} catch (JSONException e) {
e.printStackTrace();
}
}
latestAdapter.notifyDataSetChanged();
}
}, new BaseRequest.ErrorResponseCallback() {
#Override
public void onError(Exception exception) {
}
});
}}
my Adapter class
public class LatestAdapter extends RecyclerView.Adapter<LatestAdapter.MyViewHolder> {
private ImageLoader imageLoader;
private Context context;
private String text;
private List<LatestAdDetails> latestAddDetailsList;
public LatestAdapter(List<LatestAdDetails> latestAddDetailsList) {
this.latestAddDetailsList = latestAddDetailsList;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView txtTitle, txtDescription, txtCityName, txtPrice, txtCategory, txtHour, txtPhotoNo;
private NetworkImageView imgPhoto;
public MyViewHolder(View itemView) {
super(itemView);
txtTitle = (TextView) itemView.findViewById(R.id.txt_title_fad);
txtDescription = (TextView) itemView.findViewById(R.id.description_fad);
txtCityName = (TextView) itemView.findViewById(R.id.city_name_fad);
txtPrice = (TextView) itemView.findViewById(R.id.price_fad);
txtCategory = (TextView) itemView.findViewById(R.id.category_fad);
txtHour = (TextView) itemView.findViewById(R.id.hours_fad);
txtPhotoNo = (TextView) itemView.findViewById(R.id.txt_photo_no_fad);
imgPhoto = (NetworkImageView) itemView.findViewById(R.id.img_photo_lod_fad);
}
}
public void clear() {
latestAddDetailsList.clear();
notifyDataSetChanged();
}// Add a list of items
public void addAll(List<LatestAdDetails> list) {
latestAddDetailsList.addAll(list);
notifyDataSetChanged();
}
#Override
public LatestAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.featured_ad_adapter_layout, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(LatestAdapter.MyViewHolder holder, int position) {
LatestAdDetails latestAddDetails = latestAddDetailsList.get(position);
holder.txtTitle.setText(translate(latestAddDetails.getTitle()));
holder.txtDescription.setText(translate(latestAddDetails.getDescription()));
holder.txtCityName.setText(translate(latestAddDetails.getCityName()));
holder.txtPrice.setText(Integer.toString(latestAddDetails.getPrice()));
holder.txtCategory.setText(translate(latestAddDetails.getCategoryName()));
holder.txtHour.setText(Integer.toString(latestAddDetails.getCreated()));
holder.txtPhotoNo.setText(Integer.toString(0) + " photos ");
try {
imageLoader = VolleyHandler.getImageLoader();
} catch (Exception e) {
e.printStackTrace();
}
holder.imgPhoto.setImageUrl(latestAddDetails.getDefault_photo(), imageLoader);
}
#Override
public int getItemCount() {
Log.e("size", String.valueOf(latestAddDetailsList.size()));
return latestAddDetailsList.size();
}
private String translate(String myString) {
try {
myString = myString.replace("\n", "").replace("\r", "");
byte[] utf8Bytes = myString.getBytes("UTF8");
text = new String(utf8Bytes, "UTF8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return text;
}}
on refreshing adapter size is zero,but getting json correctly,but not adding to adapter,and the recycler view is not showing new data,please help me ,the json is giving 10 datas on every swipe but it is not getting added to recyclerview
It seems like a logical bug :
In method : refreshLatestAd(), Remove these line :
latestAdapter.clear();
latestAdapter.addAll(latestAdDetailsList);
and
recyclerLatest.setAdapter(latestAdapter); // It need not be set again.
Let me know if it helps.
latestAdapter.notifyDataSetChanged() is sufficient to notify the
adapter that the data is changed. Always modify the list
[latestAdDetailsList] which is being set to adapter, this is the sure
shot way to make the changes reflect when you call notifyDataSetChanged.

How to sync WebService operation in silverlight?

I am now on a project regarding controlling devices by using silverlight and web service(asmx page). The project flows like below:
pressing the button on the silverlight UI, it will send out a package by using socket to the middlewire. Then middlewire will accept the package and deconstructe it and return back another package to silverlight UI. I am using below code to load the button state, which will trigger database query:
private ButtonStateModel _buttonStateModel = new ButtonStateModel() { BtnOneImage = "Skins/images/flag/QU.png", BtnOneVisible = Visibility.Visible, BtnTwoVisible = Visibility.Collapsed };
public ButtonStateModel ButtonStateModel
{
get
{
ButtonStateModel btnState = null;
dataService.GetPR(BusEquipmentPermission.Control.RtuID, BusEquipmentPermission.Control.DevID, (result) =>
{
if (result != null && result.Count > 0)
{
var flag = result[0].PRFlag;
if (flag == 1)
{
btnState = new ButtonStateModel()
{
BtnOneImage = "Skins/images/flag/OP.png",
BtnOneVisible = Visibility.Visible,
BtnTwoImage = "Skins/images/flag/OFF.png",
BtnTwoVisible = Visibility.Visible
};
}
else if (flag == 2)
{
btnState = new ButtonStateModel()
{
BtnOneImage = "Skins/images/flag/OFF.png",
BtnOneVisible = Visibility.Visible,
BtnTwoImage = "Skins/images/flag/OR.png",
BtnTwoVisible = Visibility.Visible
};
}
}
});
return btnState;
}
set
{
if (value == _buttonStateModel)
{
return;
}
_buttonStateModel = value;
RaisePropertyChanged("ButtonStateModel");
}
}
Now the problem is, whenever I load the silverlight app, the button on the UI can't load its state correctly. I know the reason is because that the GetPR function is from webservice(asmx), it's very oddly that I can't do sync operation by using AutoResetEvent in silverlight generated client code:
public void GetPR(string rtuID, string devID, Action<List<BusControlPR>> action)
{
ServiceSoapClient proxy = new ServiceSoapClient();
proxy.GetPRAsync(rtuID, devID);
proxy.GetPRCompleted += (sender, args) =>
{
//I cannt do Sync Operation Here by using AutoResetEvent.
if (action != null)
action(args.Result.ToList());
};
}
I am using webservice (asmx page) instead of WCF ria service.
Above problem is what i meet, Anyone can give me some light?
The "GetPR" method is still running asynchronously, so the "ButtonStateModel" getter will return null immediately (the "completed" action will then have no effect). And, you do not want to use any kind of blocking inside your getters, as that will block the UI. Instead, you should put the "GetPR" in the initialization, and use the to set the "ButtonStateModel" property to the appropriate value:
public class TheViewModel
{
public ButtonStateModel ButtonStateModel
{
get
{
return _buttonStateModel;
}
set
{
if (value == _buttonStateModel)
{
return;
}
_buttonStateModel = value;
RaisePropertyChanged("ButtonStateModel");
}
}
public TheViewModel()
{
Initialize();
}
private void Initialize()
{
dataService.GetPR(BusEquipmentPermission.Control.RtuID, BusEquipmentPermission.Control.DevID, (result) =>
{
ButtonStateModel btnState = null;
if (result != null && result.Count > 0)
{
var flag = result[0].PRFlag;
if (flag == 1)
{
btnState = new ButtonStateModel()
{
BtnOneImage = "Skins/images/flag/OP.png",
BtnOneVisible = Visibility.Visible,
BtnTwoImage = "Skins/images/flag/OFF.png",
BtnTwoVisible = Visibility.Visible
};
}
else if (flag == 2)
{
btnState = new ButtonStateModel()
{
BtnOneImage = "Skins/images/flag/OFF.png",
BtnOneVisible = Visibility.Visible,
BtnTwoImage = "Skins/images/flag/OR.png",
BtnTwoVisible = Visibility.Visible
};
}
}
ButtonStateModel = btnState;
});
}
}

I have multiple image path (URI/String) how do i upload them to Amazon S3

I have multiple image's path (URI / String). By passing this value to " S3PutObjectTask().execute(URI); " i want to upload all those images to Amazon S3.
Could some one help me how to pass those URIs also how to upload multiple images.
Similar log cat error is found in android upload image to amazon storage with image path
Thanks in advance
public class AWSUpload extends Activity {
private AmazonS3Client s3Client = new AmazonS3Client(
new BasicAWSCredentials(Constants.ACCESS_KEY_ID,
Constants.SECRET_KEY));
String uri1a, uri2a, uri3a, uri4a;
int i;
private static final int PHOTO_SELECTED = 1;
Button b1;
TextView t1, t2, t3, t4;
ImageView iv1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.inspectionreport);
s3Client.setRegion(Region.getRegion(Regions.US_WEST_2));
Intent gettingURI = getIntent();
uri1a = gettingURI.getStringExtra("uri1");
uri2a = gettingURI.getStringExtra("uri2");
uri3a = gettingURI.getStringExtra("uri3");
uri4a = gettingURI.getStringExtra("uri4");
b1 = (Button) findViewById(R.id.button1);
t1 = (TextView) findViewById(R.id.textView1);
t2 = (TextView) findViewById(R.id.textView2);
t3 = (TextView) findViewById(R.id.textView3);
t4 = (TextView) findViewById(R.id.textView4);
iv1 = (ImageView) findViewById(R.id.imageView1);
Uri img1URI = Uri.parse(uri1a);
Uri img2URI = Uri.parse(uri2a);
Uri img3URI = Uri.parse(uri3a);
Uri img4URI = Uri.parse(uri4a);
t1.setText(uri1a);
t2.setText(uri2a);
t3.setText(uri3a);
t4.setText(uri4a);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
for (i = 1; i <= 4; i++) {
if (i == 1) {
Uri selectedImage1 = Uri.parse(uri1a);
new S3PutObjectTask().execute(selectedImage1);
} else if (i == 2) {
Uri selectedImage2 = Uri.parse(uri2a);
new S3PutObjectTask().execute(selectedImage2);
} else if (i == 3) {
Uri selectedImage3 = Uri.parse(uri3a);
new S3PutObjectTask().execute(selectedImage3);
} else if (i == 4) {
Uri selectedImage4 = Uri.parse(uri4a);
new S3PutObjectTask().execute(selectedImage4);
} else {
Intent returnIntent = new Intent(AWSUpload.this,
ProductImagesss.class);
startActivity(returnIntent);
}
}
}
});
}
// This method is automatically called by the image picker when an image is
// selected.
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case PHOTO_SELECTED:
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
new S3PutObjectTask().execute(selectedImage);
}
}
}
// Display an Alert message for an error or failure.
protected void displayAlert(String title, String message) {
AlertDialog.Builder confirm = new AlertDialog.Builder(this);
confirm.setTitle(title);
confirm.setMessage(message);
confirm.setNegativeButton(AWSUpload.this.getString(R.string.ok),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
confirm.show().show();
}
protected void displayErrorAlert(String title, String message) {
AlertDialog.Builder confirm = new AlertDialog.Builder(this);
confirm.setTitle(title);
confirm.setMessage(message);
confirm.setNegativeButton(AWSUpload.this.getString(R.string.ok),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
AWSUpload.this.finish();
}
});
confirm.show().show();
}
private class S3PutObjectTask extends AsyncTask<Uri, Void, S3TaskResult> {
ProgressDialog dialog;
protected void onPreExecute() {
dialog = new ProgressDialog(AWSUpload.this);
dialog.setMessage(AWSUpload.this.getString(R.string.uploading));
dialog.setCancelable(false);
dialog.show();
}
protected S3TaskResult doInBackground(Uri... uris) {
if (uris == null || uris.length != 1) {
return null;
}
// The file location of the image selected.
Uri selectedImage = uris[0];
ContentResolver resolver = getContentResolver();
String fileSizeColumn[] = { OpenableColumns.SIZE };
Cursor cursor = resolver.query(selectedImage, fileSizeColumn, null,
null, null);
cursor.moveToFirst();
int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
String size = null;
if (!cursor.isNull(sizeIndex)) {
size = cursor.getString(sizeIndex);
}
cursor.close();
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentType(resolver.getType(selectedImage));
if (size != null) {
metadata.setContentLength(Long.parseLong(size));
}
S3TaskResult result = new S3TaskResult();
// Put the image data into S3.
try {
// s3Client.createBucket(Constants.getPictureBucket());
PutObjectRequest por = new PutObjectRequest("mybucket",
Constants.PICTURE_NAME,
resolver.openInputStream(selectedImage), metadata);
s3Client.putObject(por);
} catch (Exception exception) {
result.setErrorMessage(exception.getMessage());
}
return result;
}
protected void onPostExecute(S3TaskResult result) {
dialog.dismiss();
if (result.getErrorMessage() != null) {
displayErrorAlert(
AWSUpload.this.getString(R.string.upload_failure_title),
result.getErrorMessage());
}
}
}
private class S3TaskResult {
String errorMessage = null;
Uri uri = null;
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public Uri getUri() {
return uri;
}
public void setUri(Uri uri) {
this.uri = uri;
}
}
}
My Log Cat:
E/AndroidRuntime(18015): FATAL EXCEPTION: AsyncTask #3
E/AndroidRuntime(18015): java.lang.RuntimeException: An error occured while executing doInBackground()
E/AndroidRuntime(18015): at android.os.AsyncTask$3.done(AsyncTask.java:299)
E/AndroidRuntime(18015): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
E/AndroidRuntime(18015): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
E/AndroidRuntime(18015): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
E/AndroidRuntime(18015): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
E/AndroidRuntime(18015): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
E/AndroidRuntime(18015): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
E/AndroidRuntime(18015): at java.lang.Thread.run(Thread.java:838)
E/AndroidRuntime(18015): Caused by: java.lang.NullPointerException
E/AndroidRuntime(18015): at com.cbazaarqc.AWSUpload$S3PutObjectTask.doInBackground(AWSUpload.java:229)
E/AndroidRuntime(18015): at com.cbazaarqc.AWSUpload$S3PutObjectTask.doInBackground(AWSUpload.java:1)
E/AndroidRuntime(18015): at android.os.AsyncTask$2.call(AsyncTask.java:287)
E/AndroidRuntime(18015): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
E/AndroidRuntime(18015): ... 4 more
E/WindowManager(18015): Activity com.cbazaarqc.AWSUpload has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{420a16e0 V.E..... R......D 0,0-684,192} that was originally added here
E/WindowManager(18015): android.view.WindowLeaked: Activity com.cbazaarqc.AWSUpload has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{420a16e0 V.E..... R......D 0,0-684,192} that was originally added here
E/WindowManager(18015): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:409)
E/WindowManager(18015): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:218)
E/WindowManager(18015): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
E/WindowManager(18015): at android.app.Dialog.show(Dialog.java:281)
E/WindowManager(18015): at com.cbazaarqc.AWSUpload$S3PutObjectTask.onPreExecute(AWSUpload.java:211)
E/WindowManager(18015): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
E/WindowManager(18015): at android.os.AsyncTask.execute(AsyncTask.java:534)
E/WindowManager(18015): at com.cbazaarqc.AWSUpload.onCreate(AWSUpload.java:93)
E/WindowManager(18015): at android.app.Activity.performCreate(Activity.java:5122)
E/WindowManager(18015): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
E/WindowManager(18015): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
E/WindowManager(18015): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358)
E/WindowManager(18015): at android.app.ActivityThread.access$600(ActivityThread.java:156)
E/WindowManager(18015): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1340)
E/WindowManager(18015): at android.os.Handler.dispatchMessage(Handler.java:99)
E/WindowManager(18015): at android.os.Looper.loop(Looper.java:153)
E/WindowManager(18015): at android.app.ActivityThread.main(ActivityThread.java:5297)
E/WindowManager(18015): at java.lang.reflect.Method.invokeNative(Native Method)
E/WindowManager(18015): at java.lang.reflect.Method.invoke(Method.java:511)
E/WindowManager(18015): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
E/WindowManager(18015): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
E/WindowManager(18015): at dalvik.system.NativeStart.main(Native Method)

LinkedIn Connections List code is Required for android application

I am new In android and currently working on a project which shows different friend list of different social network.
But Here at the stage I am fail to get LinkedIn Connections List and I have searched rest of the Internet but couldn't find any way. . .
If anyone know the code please help me. . . thanks in advance. .
Cheer!
Sample code is here Bellow. . .
final LinkedInOAuthService oAuthService = LinkedInOAuthServiceFactory
.getInstance().createLinkedInOAuthService(
Config.LINKEDIN_CONSUMER_KEY,Config.LINKEDIN_CONSUMER_SECRET, Config.scopeParams);
final LinkedInApiClientFactory factory = LinkedInApiClientFactory
.newInstance(Config.LINKEDIN_CONSUMER_KEY,
Config.LINKEDIN_CONSUMER_SECRET);
LinkedInRequestToken liToken;
LinkedInApiClient client;
LinkedInAccessToken accessToken = null;
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if( Build.VERSION.SDK_INT >= 9){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
share = (Button) findViewById(R.id.share);
name = (TextView) findViewById(R.id.name);
et = (EditText) findViewById(R.id.et_share);
login = (Button) findViewById(R.id.login);
photo = (ImageView) findViewById(R.id.photo);
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
linkedInLogin();
}
});
// share on linkedin
share.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String share = et.getText().toString();
if (null != share && !share.equalsIgnoreCase("")) {
OAuthConsumer consumer = new CommonsHttpOAuthConsumer(Config.LINKEDIN_CONSUMER_KEY, Config.LINKEDIN_CONSUMER_SECRET);
consumer.setTokenWithSecret(accessToken.getToken(), accessToken.getTokenSecret());
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost("https://api.linkedin.com/v1/people/~/shares");
try {
consumer.sign(post);
} catch (OAuthMessageSignerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthCommunicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // here need the consumer for sign in for post the share
post.setHeader("content-type", "text/XML");
String myEntity = "<share><comment>"+ share +"</comment><visibility><code>anyone</code></visibility></share>";
try {
post.setEntity(new StringEntity(myEntity));
org.apache.http.HttpResponse response = httpclient.execute(post);
Toast.makeText(LinkedInSampleActivity.this,
"Shared sucessfully", Toast.LENGTH_SHORT).show();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
Toast.makeText(LinkedInSampleActivity.this,
"Please enter the text to share",
Toast.LENGTH_SHORT).show();
}
/*String share = et.getText().toString();
if (null != share && !share.equalsIgnoreCase("")) {
client = factory.createLinkedInApiClient(accessToken);
client.postNetworkUpdate(share);
et.setText("");
Toast.makeText(LinkedInSampleActivity.this,
"Shared sucessfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(LinkedInSampleActivity.this,
"Please enter the text to share",
Toast.LENGTH_SHORT).show();
}*/
}
});
}
private void linkedInLogin() {
ProgressDialog progressDialog = new ProgressDialog(
LinkedInSampleActivity.this);
LinkedinDialog d = new LinkedinDialog(LinkedInSampleActivity.this,
progressDialog);
d.show();
// set call back listener to get oauth_verifier value
d.setVerifierListener(new OnVerifyListener() {
#Override
public void onVerify(String verifier) {
try {
Log.i("LinkedinSample", "verifier: " + verifier);
accessToken = LinkedinDialog.oAuthService
.getOAuthAccessToken(LinkedinDialog.liToken,
verifier);
LinkedinDialog.factory.createLinkedInApiClient(accessToken);
client = factory.createLinkedInApiClient(accessToken);
// client.postNetworkUpdate("Testing by Mukesh!!! LinkedIn wall post from Android app");
Log.i("LinkedinSample",
"ln_access_token: " + accessToken.getToken());
Log.i("LinkedinSample",
"ln_access_token: " + accessToken.getTokenSecret());
Person p = client.getProfileForCurrentUser();
name.setText("Welcome " + p.getFirstName() + " "
+ p.getLastName());
name.setVisibility(0);
login.setVisibility(4);
share.setVisibility(0);
et.setVisibility(0);
} catch (Exception e) {
Log.i("LinkedinSample", "error to get verifier");
e.printStackTrace();
}
}
});
// set progress dialog
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(true);
progressDialog.show();
}
}
try this get user-Connections
public class LinkCon_Main extends BaseActivityListView {
final LinkedInOAuthService oAuthService = LinkedInOAuthServiceFactory
.getInstance().createLinkedInOAuthService(Config.CONSUMER_KEY,
Config.CONSUMER_SECRET);
final LinkedInApiClientFactory factory = LinkedInApiClientFactory
.newInstance(Config.CONSUMER_KEY, Config.CONSUMER_SECRET);
ProgressDialog mPrograss;
String name;
View experiencePage;
TextView prof_Name, prof_Headline, prof_Location, prof_Industry;
String prof_name, prof_headline, prof_location, prof_industry, prof_summary, prof_experience,prof_education,prof_languages,prof_skills, prof_interests,prof_birthdate,prof_contatct,prof_email;
String con_name, con_headline, con_location,con_industry, con_summary,con_experience,con_education,con_languages,con_skills,con_interets,con_birthdate,con_phone;
Connections con_email;
String pic_url,con_pic_url;
String startDate, endDate;
String item;
String dty;
String dtm;
String dtd;
ImageView person_Pic, con_pic;
Map<SearchParameter, String> searchParameters;
ListView connections_list;
ArrayList<Person> itemslist;
#SuppressWarnings({ "rawtypes" })
Iterator localIterator;
Person mylist;
RelativeLayout layout_persondetils,layout_con_profile;
LinkedInApiClient client;
Person person;
Connections connections;
ImageLoader imageLoader;
DisplayImageOptions options;
LinkConApp myLinkCon;
LayoutInflater inflater;
String[] months= {"Jan", "Feb", "March", "April", "May","June", "July", "August","Sep", "Oct", "Nov", "Dec"};
StringBuilder localStringBuilder;
#Override
#SuppressLint("NewApi")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myLinkCon=new LinkConApp();
prof_Name=(TextView)findViewById(R.id.user_name);
prof_Headline=(TextView)findViewById(R.id.user_headline);
prof_Location=(TextView)findViewById(R.id.user_Location);
prof_Industry=(TextView)findViewById(R.id.user_industry);
person_Pic=(ImageView)findViewById(R.id.profile_pic);
layout_persondetils=(RelativeLayout)findViewById(R.id.layout_profiledetils);
layout_con_profile=(RelativeLayout)findViewById(R.id.layout_con_profile);
layout_persondetils.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
userpersons();
}
});
mPrograss=new ProgressDialog(LinkCon_Main.this);
inflater=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// ImageLoader options
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_launcher)
.showImageForEmptyUri(R.drawable.photo)
.showImageOnFail(R.drawable.ic_launcher).cacheInMemory(true)
.cacheOnDisc(true).considerExifParams(true).build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(this));
connections_list=(ListView)findViewById(R.id.connectionslist);
itemslist = new ArrayList<Person>();
if( Build.VERSION.SDK_INT >= 9){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
final SharedPreferences pref = getSharedPreferences(Config.OAUTH_PREF,
MODE_PRIVATE);
final String token = pref.getString(Config.PREF_TOKEN, null);
final String tokenSecret = pref.getString(Config.PREF_TOKENSECRET, null);
if (token == null || tokenSecret == null) {
startAutheniticate();
} else {
showCurrentUser(new LinkedInAccessToken(token, tokenSecret));
}
}
void startAutheniticate() {
mPrograss.setMessage("Loading...");
mPrograss.setCancelable(true);
mPrograss.show();
new AsyncTask<Void, Void, LinkedInRequestToken>() {
#Override
protected LinkedInRequestToken doInBackground(Void... params) {
return oAuthService.getOAuthRequestToken(Config.OAUTH_CALLBACK_URL);
}
#Override
protected void onPostExecute(LinkedInRequestToken liToken) {
final String uri = liToken.getAuthorizationUrl();
getSharedPreferences(Config.OAUTH_PREF, MODE_PRIVATE)
.edit()
.putString(Config.PREF_REQTOKENSECRET,
liToken.getTokenSecret()).commit();
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(i);
}
}.execute();
mPrograss.dismiss();
}
void finishAuthenticate(final Uri uri) {
if (uri != null && uri.getScheme().equals(Config.OAUTH_CALLBACK_SCHEME)) {
final String problem = uri.getQueryParameter(Config.OAUTH_QUERY_PROBLEM);
if (problem == null) {
new AsyncTask<Void, Void, LinkedInAccessToken>() {
#Override
protected LinkedInAccessToken doInBackground(Void... params) {
final SharedPreferences pref = getSharedPreferences(
Config.OAUTH_PREF, MODE_PRIVATE);
final LinkedInAccessToken accessToken = oAuthService
.getOAuthAccessToken(
new LinkedInRequestToken(
uri.getQueryParameter(Config.OAUTH_QUERY_TOKEN),
pref.getString(
Config.PREF_REQTOKENSECRET,
null)),
uri.getQueryParameter(Config.OAUTH_QUERY_VERIFIER));
pref.edit()
.putString(Config.PREF_TOKEN, accessToken.getToken())
.putString(Config.PREF_TOKENSECRET,
accessToken.getTokenSecret())
.remove(Config.PREF_REQTOKENSECRET).commit();
return accessToken;
}
#Override
protected void onPostExecute(LinkedInAccessToken accessToken) {
mPrograss.dismiss();
showCurrentUser(accessToken);
}
}.execute();
} else {
Toast.makeText(this,
"Appliaction down due OAuth problem: " + problem,
Toast.LENGTH_LONG).show();
finish();
}
}
}
void clearTokens() {
getSharedPreferences(Config.OAUTH_PREF, MODE_PRIVATE).edit()
.remove(Config.PREF_TOKEN).remove(Config.PREF_TOKENSECRET)
.remove(Config.PREF_REQTOKENSECRET).commit();
}
void showCurrentUser(final LinkedInAccessToken accessToken) {
client = factory.createLinkedInApiClient(accessToken);
mPrograss.setMessage("Loading..");
mPrograss.show();
new AsyncTask<Void, Void, Object>() {
#Override
protected Object doInBackground(Void... params) {
try {
final Person user_Profile = client.getProfileForCurrentUser(EnumSet.of(ProfileField.ID));
person = client.getProfileById(user_Profile.getId(), EnumSet.of(
ProfileField.FIRST_NAME,
ProfileField.LAST_NAME,
ProfileField.PICTURE_URL,
ProfileField.INDUSTRY,
ProfileField.MAIN_ADDRESS,
ProfileField.HEADLINE,
ProfileField.SUMMARY,
ProfileField.POSITIONS,
ProfileField.EDUCATIONS,
ProfileField.LANGUAGES,
ProfileField.SKILLS,
ProfileField.INTERESTS,
ProfileField.PHONE_NUMBERS,
ProfileField.EMAIL_ADDRESS,
ProfileField.DATE_OF_BIRTH,
ProfileField.PUBLIC_PROFILE_URL));
prof_name = person.getFirstName() + " " + person.getLastName();
prof_headline = person.getHeadline();
prof_location = person.getMainAddress();
prof_industry = person.getIndustry();
return person;
} catch (LinkedInApiClientException ex) {
return ex;
}
}
#Override
protected void onPostExecute(Object result) {
if (result instanceof Exception) {
//result is an Exception :)
final Exception ex = (Exception) result;
clearTokens();
Toast.makeText(
LinkCon_Main.this,
"Appliaction down due LinkedInApiClientException: "
+ ex.getMessage()
+ " Authokens cleared - try run application again.",
Toast.LENGTH_LONG).show();
finish();
} else if (result instanceof Person) {
final Person person = (Person) result;
prof_Name.setText( person.getFirstName() + " " + person.getLastName());
prof_Headline.setText(person.getHeadline());
prof_Location.setText(person.getMainAddress());
prof_Industry.setText(person.getIndustry());
prof_Name.setVisibility(0);
prof_Headline.setVisibility(0);
prof_Location.setVisibility(0);
prof_Industry.setVisibility(0);
person_Pic.setVisibility(0);
userConnections();
userDetails();
}
}
}.execute();
mPrograss.dismiss();
}
#Override
protected void onNewIntent(Intent intent) {
finishAuthenticate(intent.getData());
}
public void userDetails(){
if(person.getPictureUrl()!=null){
pic_url = person.getPictureUrl().toString();
imageLoader.displayImage(pic_url, person_Pic);
}else{
person_Pic.setImageResource(R.drawable.ic_launcher);
}
/*************** person Details Summary/experience/education/languages/skills/contacts/interests **********************/
if (person.getSummary()!=null) {
prof_summary = person.getSummary();
}
prof_experience="";
for (Position position:person.getPositions().getPositionList())
{
if(position.isIsCurrent()){
startDate=months[(int) (position.getStartDate().getMonth()-1)]+"-"+position.getStartDate().getYear();
endDate="Currently Working";
}else{
startDate=months[(int) (position.getStartDate().getMonth()-1)]+"-"+position.getStartDate().getYear();
endDate=months[(int) (position.getEndDate().getMonth()-1)]+"-"+position.getEndDate().getYear();
}
prof_experience=prof_experience+"<b>" +"Position :"+"</b>"+position.getTitle()+"<br><b>" +"Company :"+ "</b>"+ position.getCompany().getName()+"<br><b>" +"Start Date:"+ "</b>"+ startDate +"<br><b>" +"End Date:"+ "</b>"+ endDate +"<br>"+"<br>";
}
prof_education="";
for (Education education:person.getEducations().getEducationList())
{
prof_education=prof_education +"<b>" +"Gaduation :"+ "</b>" +education.getDegree()+"<br><b>" +"Institute :"+ "</b>" +education.getSchoolName()+ "<br><b>" +"Graduation Year :"+ "</b>" +education.getEndDate().getYear()+"<br>"+"<br>";
}
prof_languages="";
for(Language language:person.getLanguages().getLanguageList())
{
prof_languages=prof_languages+language.getLanguage().getName()+"\n";
}
prof_skills="";
for(Skill skill:person.getSkills().getSkillList())
{
prof_skills=prof_skills+skill.getSkill().getName()+"\n";
}
prof_contatct="";
PhoneNumbers contactinfo=person.getPhoneNumbers();
if(contactinfo!=null ){
for(PhoneNumber phoneno:person.getPhoneNumbers().getPhoneNumberList())
{
prof_contatct=prof_contatct+ phoneno.getPhoneNumber().toString();
}
}
if(person.getEmailAddress()!=null){
prof_email=person.getEmailAddress();
}
prof_interests = person.getInterests();
prof_birthdate= person.getDateOfBirth().getDay()+"-"+ months[(int) (person.getDateOfBirth().getMonth()-1)]+"-"+person.getDateOfBirth().getYear();
}
public void userConnections(){
final Set<ProfileField> connectionFields = EnumSet.of(ProfileField.ID,
ProfileField.FIRST_NAME,
ProfileField.LAST_NAME,
ProfileField.HEADLINE,
ProfileField.INDUSTRY,
ProfileField.PICTURE_URL,
ProfileField.MAIN_ADDRESS,
ProfileField.LOCATION,
ProfileField.LOCATION_COUNTRY,
ProfileField.LOCATION_NAME,
ProfileField.SUMMARY,
ProfileField.EDUCATIONS,
ProfileField.EDUCATIONS_DEGREE,
ProfileField.EDUCATIONS_END_DATE,
ProfileField.EDUCATIONS_FIELD_OF_STUDY,
ProfileField.EDUCATIONS_ID,
ProfileField.EDUCATIONS_SCHOOL_NAME,
ProfileField.EDUCATIONS_START_DATE,
ProfileField.LANGUAGES,
ProfileField.LANGUAGES_ID,
ProfileField.LANGUAGES_LANGUAGE,
ProfileField.LANGUAGES_LANGUAGE_NAME,
ProfileField.POSITIONS,
ProfileField.POSITIONS_COMPANY,
ProfileField.POSITIONS_COMPANY_INDUSTRY,
ProfileField.POSITIONS_COMPANY_NAME,
ProfileField.POSITIONS_END_DATE,
ProfileField.POSITIONS_IS_CURRENT,
ProfileField.POSITIONS_START_DATE,
ProfileField.POSITIONS_SUMMARY,
ProfileField.POSITIONS_TITLE,
ProfileField.SKILLS,
ProfileField.INTERESTS,
ProfileField.PHONE_NUMBERS,
ProfileField.EMAIL_ADDRESS,
ProfileField.DATE_OF_BIRTH,
ProfileField.PUBLIC_PROFILE_URL
);
connections = client.getConnectionsForCurrentUser(connectionFields);
for (Person person : connections.getPersonList()) {
itemslist.add(person);
}
connection_Adapter myadpter=new connection_Adapter();
connections_list.setAdapter(myadpter);
connections_list.setVisibility(0);
connections_list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/*Connections List item position selection*/
person = itemslist.get(position);
/*
Map<SearchParameter, String> searchParameters = new EnumMap<SearchParameter, String>(SearchParameter.class);
searchParameters.put(SearchParameter.KEYWORDS, "University of X");
People people = client.searchPeople(searchParameters);
System.out.println("Total search result:" + people.getCount());
for (Person person : people.getPersonList()) {
System.out.println(person.getId() + ":" + person.getFirstName() + " " +
person.getLastName() + ":" + person.getHeadline());
}*/
/*
People people = client.searchPeople(searchParameters);
for (Person persons : people.getPersonList()) {
persons = client.getProfileByApiRequest(persons.getApiStandardProfileRequest());
}
Log.i("My Persons list", ""+person);*/
/*Intent mycon=new Intent(LinkCon_Main.this, Con_Profile.class);
mycon.putExtra("conid", con_name);
startActivity(mycon);
*/
con_name=person.getFirstName()+" "+person.getLastName();
System.out.println("Name:"+con_name);
con_headline=person.getHeadline();
System.out.println("Designation:"+con_headline);
con_industry=person.getIndustry();
System.out.println("Industry:"+con_industry);
Location localLocation = person.getLocation();
if (localLocation != null){
con_location=String.format("%s", new Object[] { localLocation.getName() });
System.out.println("Con_Loaction:"+con_location);
}
/*****PICTURE/NAME/INDUSTRY/LOCATION Tested OK******/
/********need to get SUMMARY/EXPERIENCE/EDUCATION/SKILLS/LANGUAGES/DATEOFBIRTH/PHONENUMBER/EMAIL**********/
Toast.makeText(LinkCon_Main.this, "Name:"+" "+con_name +"\n"+"Position:"+" "+con_headline+"\n"+"Industry:"+" "+con_industry+"\n"+"Locations:"+" "+con_location, Toast.LENGTH_LONG).show();
}//onItemClick
});
}
public class connection_Adapter extends BaseAdapter{
#Override
public int getCount() {
// TODO Auto-generated method stub
return itemslist.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder = null;
if(convertView==null){
convertView = inflater.inflate(R.layout.list_row,
null);
holder = new ViewHolder();
holder.con_Itenames = (TextView) convertView
.findViewById(R.id.connection_name);
holder.con_designations = (TextView) convertView
.findViewById(R.id.connection_headline);
holder.con_ItemImage = (ImageView) convertView
.findViewById(R.id.connection_image);
holder.con_locationad = (TextView) convertView
.findViewById(R.id.connection_location);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
SetData(holder,position);
return convertView;
}
protected Context getBaseContext() {
// TODO Auto-generated method stub
return null;
}
public void SetData(final ViewHolder holder, int position) {
final Person con_details = itemslist.get(position);
holder.con_Itenames.setText(con_details.getFirstName()+" "+con_details.getLastName());
holder.con_designations.setText(con_details.getIndustry());
Location localLocation = con_details.getLocation();
if (localLocation != null){
con_location=String.format("%s", new Object[] { localLocation.getName() });
}
holder.con_locationad.setText(con_location);
holder.con_Itenames.setTag(con_details);
if (con_details.getPictureUrl()!=null) {
imageLoader.displayImage(con_details.getPictureUrl(), holder.con_ItemImage, options);
}else {
holder.con_ItemImage.setImageResource(R.drawable.ic_launcher);}
}
public void setListItems(ArrayList<Person> newList) {
itemslist = newList;
notifyDataSetChanged();
}
}
public class ViewHolder{
TextView con_Itenames,con_designations, con_locationad;
ImageView con_ItemImage;
}
private void userpersons() {
// TODO Auto-generated method stub
Intent user_prof = new Intent(LinkCon_Main.this, User_Profile.class);
user_prof.putExtra("pic", pic_url);
user_prof.putExtra("name", prof_name);
user_prof.putExtra("headline", prof_headline);
user_prof.putExtra("locations", prof_location);
user_prof.putExtra("industry", prof_industry);
user_prof.putExtra("summary", prof_summary);
user_prof.putExtra("languages", prof_languages);
user_prof.putExtra("experience", prof_experience);
user_prof.putExtra("education", prof_education);
user_prof.putExtra("skills", prof_skills);
user_prof.putExtra("interests", prof_interests);
user_prof.putExtra("dateofbirth", prof_birthdate);
user_prof.putExtra("phoneno", prof_contatct);
user_prof.putExtra("email", prof_email);
startActivity(user_prof);
}
}