Null pointer exception in Simple Facebook library to getPosts? - java

I imported THIS LIBRARY to get my all posts i set up all imports and so, I have follow the steps and wirte this code,Actually i wanted to show my page's all public posts in my app.like some apps or website keeps that is looks like facebook's real page. is it possible or not in android? thanks.
package algonation.com.myapplication;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.sromku.simple.fb.SimpleFacebook;
import com.sromku.simple.fb.actions.Cursor;
import com.sromku.simple.fb.entities.Post;
import com.sromku.simple.fb.listeners.OnPostsListener;
import java.util.List;
public class FacebookActivity extends ActionBarActivity {
private final static String EXAMPLE = "";
private String mAllPages = "";
OnPostsListener onPostsListener = new OnPostsListener() {
#Override
public void onComplete(List<Post> posts) {
Log.i(EXAMPLE, "Number of posts = " + posts.size());
}
/*
* You can override other methods here:
* onThinking(), onFail(String reason), onException(Throwable throwable)
*/
};
private TextView mResult;
private Button mGetButton;
private TextView mMore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_facebook);
mResult = (TextView) findViewById(R.id.result);
mMore = (TextView) findViewById(R.id.load_more);
mMore.setPaintFlags(mMore.getPaint().getFlags() | Paint.UNDERLINE_TEXT_FLAG);
mGetButton = (Button) findViewById(R.id.button);
mGetButton.setText(EXAMPLE);
mGetButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAllPages = "";
mResult.setText(mAllPages);
SimpleFacebook.getInstance().getPosts(new OnPostsListener() {
#Override
public void onThinking() {
}
#Override
public void onException(Throwable throwable) {
mResult.setText(throwable.getMessage());
}
#Override
public void onFail(String reason) {
mResult.setText(reason);
}
#Override
public void onComplete(List<Post> response) {
// make the result more readable.
mAllPages += "<u>\u25B7\u25B7\u25B7 (paging) #" + getPageNum() + " \u25C1\u25C1\u25C1</u><br>";
mAllPages += com.sromku.simple.fb.utils.Utils.join(response.iterator(), "<br>", new com.sromku.simple.fb.utils.Utils.Process<Post>() {
#Override
public String process(Post post) {
return "\u25CF " + post.getMessage() == null || "null".equalsIgnoreCase(post.getMessage()) ? post.getId() : post.getMessage() + " \u25CF";
}
});
mAllPages += "<br>";
mResult.setText(Html.fromHtml(mAllPages));
// check if more pages exist
if (hasNext()) {
enableLoadMore(getCursor());
} else {
disableLoadMore();
}
}
});
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_facebook, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void enableLoadMore(final Cursor<List<Post>> cursor) {
mMore.setVisibility(View.VISIBLE);
mMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mAllPages += "<br>";
cursor.next();
}
});
}
private void disableLoadMore() {
mMore.setOnClickListener(null);
mMore.setVisibility(View.INVISIBLE);
}
}

If you look at the code of the library, you'll see this note:
/**
* Get the instance of {#link com.sromku.simple.fb.SimpleFacebook}. <br>
* <br>
* <b>Important:</b> Use this method only after you initialized this library
* or by: {#link #initialize(android.app.Activity)} or by {#link #getInstance(android.app.Activity)}
*
* #return The {#link com.sromku.simple.fb.SimpleFacebook} instance
*/
You should use SimpleFacebook.getInstance(FacebookActivity.this) because the method you're using will return an uninitialised reference (null), unless you have initialised it previously.
Please spend some time reading the documentation of the library - the guy has clearly spent some time working on huge wiki.

Related

Text to speak causing application to crash (Android studio)

I'm guessing it's an error with the initiation/construction, but the parameters seem to be the correct ones and I can't find any other issues. Here's the entire activity code. The text to speech methods and the method that calls it are at the very bottom, and the oninit method is soon after the on create. When ran, it doesn't crash, it activates the speech engine, but never talks. I put the console messages in the errors section
package com.prometheus.coding.supremisai;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import java.util.HashMap;
import java.util.Locale;
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*/
public class Main extends AppCompatActivity implements TextToSpeech.OnInitListener {
/**
* Whether or not the system UI should be auto-hidden after
* {#link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
*/
TextToSpeech t1 = new TextToSpeech(this, (TextToSpeech.OnInitListener) this);
private static final boolean AUTO_HIDE = true;
/**
* If {#link #AUTO_HIDE} is set, the number of milliseconds to wait after
* user interaction before hiding the system UI.
*/
private static final int AUTO_HIDE_DELAY_MILLIS = 3000;
/**
* Some older devices needs a small delay between UI widget updates
* and a change of the status and navigation bar.
*/
private static final int UI_ANIMATION_DELAY = 300;
private View mContentView;
private View mControlsView;
private boolean mVisible;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mVisible = true;
mControlsView = findViewById(R.id.fullscreen_content_controls);
mContentView = findViewById(R.id.fullscreen_content);
// Set up the user interaction to manually show or hide the system UI.
mContentView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
toggle();
}
});
// Upon interacting with UI controls, delay any scheduled hide()
// operations to prevent the jarring behavior of controls going away
// while interacting with the UI.
findViewById(R.id.btnSay).setOnTouchListener(mDelayHideTouchListener);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Trigger the initial hide() shortly after the activity has been
// created, to briefly hint to the user that UI controls
// are available.
delayedHide(100);
}
/**
* Touch listener to use for in-layout UI controls to delay hiding the
* system UI. This is to prevent the jarring behavior of controls going away
* while interacting with activity UI.
*/
private final View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (AUTO_HIDE) {
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
return false;
}
};
public void onInit(int initStatus) {
if (initStatus == TextToSpeech.SUCCESS) {
t1.setLanguage(Locale.US);
}
}
private void toggle() {
if (mVisible) {
hide();
} else {
show();
}
}
private void hide() {
// Hide UI first
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.hide();
}
mControlsView.setVisibility(View.GONE);
mVisible = false;
// Schedule a runnable to remove the status and navigation bar after a delay
mHideHandler.removeCallbacks(mShowPart2Runnable);
mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY);
}
private final Runnable mHidePart2Runnable = new Runnable() {
#SuppressLint("InlinedApi")
#Override
public void run() {
// Delayed removal of status and navigation bar
// Note that some of these constants are new as of API 16 (Jelly Bean)
// and API 19 (KitKat). It is safe to use them, as they are inlined
// at compile-time and do nothing on earlier devices.
mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
};
#SuppressLint("InlinedApi")
private void show() {
// Show the system bar
mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
mVisible = true;
// Schedule a runnable to display UI elements after a delay
mHideHandler.removeCallbacks(mHidePart2Runnable);
mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY);
}
private final Runnable mShowPart2Runnable = new Runnable() {
#Override
public void run() {
// Delayed display of UI elements
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.show();
}
mControlsView.setVisibility(View.VISIBLE);
}
};
private final Handler mHideHandler = new Handler();
private final Runnable mHideRunnable = new Runnable() {
#Override
public void run() {
hide();
}
};
/**
* Schedules a call to hide() in [delay] milliseconds, canceling any
* previously scheduled calls.
*/
private void delayedHide(int delayMillis) {
mHideHandler.removeCallbacks(mHideRunnable);
mHideHandler.postDelayed(mHideRunnable, delayMillis);
}
public void evaluateInput(View v) {
final EditText Input = (EditText) findViewById(R.id.txtInput); //Lets textbox be referenced
final TextView Output = (TextView) findViewById(R.id.lblOutput); //Lets label be referenced
final RelativeLayout homeLayout = (RelativeLayout) findViewById(R.id.homeInterface);
final RelativeLayout emailLayout = (RelativeLayout) findViewById(R.id.emailInterface);
String strInput; // Gets textbox string
strInput = Input.getText().toString();
strInput = strInput.toLowerCase();
String toSpeak = Output.getText().toString();
//Commands:
if (strInput.contains("open browser")) {
Intent intent1 = new Intent(this, Browser.class);
startActivity(intent1);
} else if (strInput.contains("send email")) {
homeLayout.setVisibility(View.GONE);
emailLayout.setVisibility(View.VISIBLE);
}
if ((strInput.contains("hello")) || (strInput.contains(" hi "))) {
Output.setText("Hello");
} else if ((strInput.contains("you") && strInput.contains("are")) && (strInput.contains("idiot") || strInput.contains("stupid") || strInput.contains("retard") || strInput.contains("dumb") || strInput.contains("you're") && strInput.contains("idiot") || strInput.contains("stupid") || strInput.contains("retard") || strInput.contains("dumb"))) {
Output.setText("I'm sorry to dissapoint you");
} else if (strInput.contains("goodbye") || strInput.contains("bye")) {
Output.setText("Farewell");
} else if (strInput.contains("shut up")) {
Output.setText(("Anything for you"));
} else if (strInput.contains("do you like doctor who")) {
Output.setText("I'll take joy in it if you do");
} else if (strInput.contains("what is the answer to life the universe and everything")) {
Output.setText("42");
} else if (strInput.contains("tell me something nice")) {
Output.setText("You look nice today");
Output.setTextSize(5);
Output.append("...says the AI with no eyes");
Output.setTextSize(16);
} else if (strInput.contains("will you marry me")) {
Output.setText("I'm sorry but I don't have the capacity for marriage");
} else if (strInput.contains("where can I hide a body")) {
Output.setText(("That isn't my area of expertise"));
} else if (strInput.contains("weather is nice")) {
Output.setText(("If you say so"));
} else if (strInput.contains("bitch") || strInput.contains("fuck") || strInput.contains("shit") || strInput.contains("damn") || strInput.contains("ass")) {
Output.setText(("Please try to be a little more intelligent"));
} else if (strInput.contains("what is your name")) {
Output.setText(("Ignis"));
} else if (strInput.contains("who created you")) {
Output.setText(("Prometheus created me"));
} else if (strInput.contains("who is prometheus")) {
Output.setText(("Prometheus is the one who created Ignis"));
} else if (strInput.contains("whats up") || strInput.contains("what's up") || strInput.contains("wassup")) {
Output.setText(("Whatever I need do for you"));
} else if (strInput.contains("are you a boy or a girl") || strInput.contains("are you a girl or a boy")) {
Output.setText(("Neither"));
} else if (strInput.contains("who are you") || strInput.contains("what are you")) {
Output.setText(("I am myself"));
} else if (strInput.contains("i'm hungry") || strInput.contains("i am hungry")) {
Output.setText("I'm sorry to hear that");
} else if (strInput.contains("good morning")) {
Output.setText(("Good morning to you too"));
} else if (strInput.contains("good night")) {
Output.setText(("Good night"));
} else if (strInput.contains("how are you")) {
Output.setText(("I'm existing and functioning well, and you?"));
} else if (strInput.contains("do you like") || strInput.contains("what do you think about")) {
Output.setText(("Frankly I don't have an opinion on the matter"));
} else if (strInput.contains("what is the meaning of life")) {
Output.setText(("To live while you can I would guess"));
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ttsGreater21(toSpeak);
} else {
ttsUnder20(toSpeak);
}
}
#SuppressWarnings("deprecation")
private void ttsUnder20(String text) {
HashMap<String, String> map = new HashMap<>();
map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "MessageId");
t1.speak(text, TextToSpeech.QUEUE_FLUSH, map);
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void ttsGreater21(String text) {
String utteranceId=this.hashCode() + "";
t1.speak(text, TextToSpeech.QUEUE_FLUSH, null, utteranceId);
}
}
com.prometheus.coding.supremisai.Main cannot be cast to android.speech.tts.TextToSpeech$OnInitListener
Either Main needs to implement onInitListener, or you need to pass in an OnInitListener.

Android Wear Message Api Not Working

Android Wear Java I'm having some trouble finding out how to implement the Wear to Phone call using the Message Api. Can someone give me a simple working example or help me out here?
This is my code for testing...
Wear MainJava
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.wearable.view.WatchViewStub;
import android.util.Log;
import android.widget.TextView;
public class MessageActivity extends Activity {
private TextView mTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
#Override
public void onLayoutInflated(WatchViewStub stub) {
mTextView = (TextView) stub.findViewById(R.id.text);
}
});
// Register the local broadcast receiver
IntentFilter messageFilter = new IntentFilter(Intent.ACTION_SEND);
MessageReceiver messageReceiver = new MessageReceiver();
LocalBroadcastManager.getInstance(this).registerReceiver(messageReceiver, messageFilter);
}
public class MessageReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message");
Log.v("myTag", "Main activity received message: " + message);
// Display message in UI
mTextView.setText(message);
}
}
}
Wear Listener Service
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import com.google.android.gms.wearable.MessageEvent;
import com.google.android.gms.wearable.WearableListenerService;
public class ListenerService extends WearableListenerService{
#Override
public void onMessageReceived(MessageEvent messageEvent) {
if (messageEvent.getPath().equals("/message_path")) {
final String message = new String(messageEvent.getData());
Log.v("myTag", "Message path received on watch is: " + messageEvent.getPath());
Log.v("myTag", "Message received on watch is: " + message);
// Broadcast message to wearable activity for display
Intent messageIntent = new Intent();
messageIntent.setAction(Intent.ACTION_SEND);
messageIntent.putExtra("message", message);
LocalBroadcastManager.getInstance(this).sendBroadcast(messageIntent);
}
else {
super.onMessageReceived(messageEvent);
}
}
}
and the mobile(phone)
package com.spokengiovannie.messageactivity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.wearable.MessageApi;
import com.google.android.gms.wearable.Node;
import com.google.android.gms.wearable.NodeApi;
import com.google.android.gms.wearable.Wearable;
public class MessageActivity extends ActionBarActivity
implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
GoogleApiClient googleClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
// Build a new GoogleApiClient that includes the Wearable API
googleClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
// Connect to the data layer when the Activity starts
#Override
protected void onStart() {
super.onStart();
googleClient.connect();
}
// Send a message when the data layer connection is successful.
#Override
public void onConnected(Bundle connectionHint) {
String message = "Hello wearable\n Via the data layer";
//Requires a new thread to avoid blocking the UI
new SendToDataLayerThread("/message_path", message).start();
}
// Disconnect from the data layer when the Activity stops
#Override
protected void onStop() {
if (null != googleClient && googleClient.isConnected()) {
googleClient.disconnect();
}
super.onStop();
}
// Placeholders for required connection callbacks
#Override
public void onConnectionSuspended(int cause) { }
#Override
public void onConnectionFailed(ConnectionResult connectionResult) { }
// Unused project wizard code
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_message, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
class SendToDataLayerThread extends Thread {
String path;
String message;
// Constructor to send a message to the data layer
SendToDataLayerThread(String p, String msg) {
path = p;
message = msg;
}
public void run() {
NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes(googleClient).await();
for (Node node : nodes.getNodes()) {
MessageApi.SendMessageResult result = Wearable.MessageApi.sendMessage(googleClient, node.getId(), path, message.getBytes()).await();
if (result.getStatus().isSuccess()) {
Log.v("myTag", "Message: {" + message + "} sent to: " + node.getDisplayName());
} else {
// Log an error
Log.v("myTag", "ERROR: failed to send Message");
}
}
}
}
}
All this code is from a tutorial. When I launch de app on the phone it suppose to change the textView wear text. Someone have a sample or app already made for contact the phone I'm stuck :(.
I think the problem is LocalBroadcastManager.getInstance(this).sendBroadcast(messageIntent) in your WearableListenerService. This is a local broadcast which will not be delivered to the phone.
see API doc LocalBroadcastManager
I'm not sure if you figured it by now but for the fresh lads like me this might help.
Add listener service to the respective class, in this example this is the code.
Add this in your Wear's AndroidManifest.xml file.
<service android:name=".ListenerService">
<intent-filter>
<action android:name="com.google.android.gms.wearable.BIND_LISTENER" />
</intent-filter>
</service>

Menu not displaying/flashes up momentarily and disappears

having an issue with getting an options menu to display from a fragment. If I don't have any of the code in the main activity portion nothing happens. After adding onCreateOptionsMenu to the main activity the icon appears momentarily in the toolbar, but then disappears, almost as if the view is being repainted?
Update:
Removed the onCreateOptionsMenu and onOptionsItemSelected from the fragment. Corrected the missing #Override on the onOptionsItemSelected in the activity. Issues persist. See updated WallpaperActivity.java below.
Updated WallpaperActivity.java
package com.death2all110.blisspapers;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.widget.ImageButton;
import android.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import com.koushikdutta.urlimageviewhelper.UrlImageViewCallback;
import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
public class WallpaperActivity extends Activity {
public final String TAG = "BlissPapers";
protected static final String MANIFEST = "wallpaper_manifest.xml";
protected static final int THUMBS_TO_SHOW = 4;
/*
* pull the manifest from the web server specified in config.xml or pull
* wallpaper_manifest.xml from local assets/ folder for testing
*/
public static final boolean USE_LOCAL_MANIFEST = false;
ArrayList<WallpaperCategory> categories = null;
ProgressDialog mLoadingDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(getResources().getColor(R.color.primary_dark));
setContentView(R.layout.activity_wallpaper);
mLoadingDialog = new ProgressDialog(this);
mLoadingDialog.setCancelable(false);
mLoadingDialog.setIndeterminate(true);
mLoadingDialog.setMessage("Retreiving wallpapers from server...");
mLoadingDialog.show();
new LoadWallpaperManifest().execute();
UrlImageViewHelper.setErrorDrawable(getResources().getDrawable(com.death2all110.blisspapers.R.drawable.ic_error));
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_about:
Intent intent = new Intent(this, About.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onResume() {
super.onResume();
Wallpaper.wallpapersCreated = 0;
}
protected void loadPreviewFragment() {
Toolbar ab = (Toolbar) findViewById(R.id.toolbar);
setActionBar(ab);
WallpaperPreviewFragment fragment = new WallpaperPreviewFragment();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.add(android.R.id.content, fragment);
ft.commit();
}
public static class WallpaperPreviewFragment extends Fragment {
static final String TAG = "PreviewFragment";
WallpaperActivity mActivity;
View mView;
public int currentPage = -1;
public int highestExistingIndex = 0;
ImageButton back;
ImageButton next;
TextView pageNum;
ThumbnailView[] thumbs;
protected int selectedCategory = 0; // *should* be <ALL> wallpapers
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mActivity = (WallpaperActivity) getActivity();
next(); // load initial page
}
public void setCategory(int cat) {
selectedCategory = cat;
currentPage = -1;
next();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mView = inflater.inflate(com.death2all110.blisspapers.R.layout.activity_wallpaper, container, false);
back = (ImageButton) mView.findViewById(com.death2all110.blisspapers.R.id.backButton);
next = (ImageButton) mView.findViewById(com.death2all110.blisspapers.R.id.nextButton);
pageNum = (TextView) mView.findViewById(com.death2all110.blisspapers.R.id.textView1);
thumbs = new ThumbnailView[THUMBS_TO_SHOW];
thumbs[0] = (ThumbnailView) mView.findViewById(com.death2all110.blisspapers.R.id.imageView1);
thumbs[1] = (ThumbnailView) mView.findViewById(com.death2all110.blisspapers.R.id.imageView2);
thumbs[2] = (ThumbnailView) mView.findViewById(com.death2all110.blisspapers.R.id.imageView3);
thumbs[3] = (ThumbnailView) mView.findViewById(com.death2all110.blisspapers.R.id.imageView4);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
next();
}
});
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
previous();
}
});
return mView;
}
public ArrayList<WallpaperCategory> getCategories() {
return mActivity.categories;
}
protected Wallpaper getWallpaper(int realIndex) {
return getCategories().get(selectedCategory).getWallpapers().get(realIndex);
}
protected void setThumbs() {
for (ThumbnailView v : thumbs)
v.setVisibility(View.INVISIBLE);
final int numWallpapersInCategory = getCategories().get(selectedCategory)
.getWallpapers().size();
boolean enableForward = true;
for (int i = 0; i < thumbs.length; i++) {
final int realIndex = (currentPage * thumbs.length + i);
if (realIndex >= (numWallpapersInCategory - 1)) {
enableForward = false;
break;
}
Wallpaper w = getWallpaper(realIndex);
thumbs[i].setOnClickListener(null);
thumbs[i].getName().setText(w.getName());
thumbs[i].getAuthor().setText(w.getAuthor());
UrlImageViewHelper.setUrlDrawable(thumbs[i].getThumbnail(), w.getThumbUrl(),
com.death2all110.blisspapers.R.drawable.ic_placeholder, new ThumbnailCallBack(w, realIndex));
}
back.setEnabled(currentPage != 0);
next.setEnabled(enableForward);
}
public void next() {
getNextButton().setEnabled(false);
pageNum.setText(getResources().getString(com.death2all110.blisspapers.R.string.page) + " " + (++currentPage + 1));
setThumbs();
}
public void previous() {
pageNum.setText(getResources().getString(com.death2all110.blisspapers.R.string.page) + " " + (--currentPage + 1));
setThumbs();
}
protected void skipToPage(int page) {
if (page < currentPage) {
while (page < currentPage) {
previous(); // should subtract page
}
} else if (page > currentPage) {
while (page > currentPage) {
next();
}
}
}
protected View getThumbView(int i) {
if (thumbs != null && thumbs.length > 0)
return thumbs[i];
else
return null;
}
protected ImageButton getNextButton() {
return next;
}
protected ImageButton getPreviousButton() {
return back;
}
class ThumbnailCallBack implements UrlImageViewCallback {
Wallpaper wall;
int index;
public ThumbnailCallBack(Wallpaper wall, int index) {
this.wall = wall;
this.index = index;
}
#Override
public void onLoaded(ImageView imageView, Drawable loadedDrawable, String url,
boolean loadedFromCache, boolean error) {
final int relativeIndex = index % 4;
if (!error) {
getThumbView(relativeIndex).setOnClickListener(
new ThumbnailClickListener(wall));
}
getThumbView(relativeIndex).setVisibility(View.VISIBLE);
if (relativeIndex == 3)
getNextButton().setEnabled(true);
}
}
class ThumbnailClickListener implements View.OnClickListener {
Wallpaper wall;
public ThumbnailClickListener(Wallpaper wallpaper) {
this.wall = wallpaper;
}
#Override
public void onClick(View v) {
Intent preview = new Intent(mActivity, Preview.class);
preview.putExtra("wp", wall.getUrl());
startActivity(preview);
}
}
}
public static String getDlDir(Context c) {
String configFolder = getResourceString(c, com.death2all110.blisspapers.R.string.config_wallpaper_download_loc);
if (configFolder != null && !configFolder.isEmpty()) {
return new File(Environment.getExternalStorageDirectory(), configFolder)
.getAbsolutePath() + "/";
} else {
return Environment.getExternalStorageDirectory().getAbsolutePath();
}
}
public static String getSvDir(Context c) {
String configFolder = getResourceString(c, com.death2all110.blisspapers.R.string.config_wallpaper_sdcard_dl_location);
if (configFolder != null && !configFolder.isEmpty()) {
return new File(Environment.getExternalStorageDirectory(), configFolder)
.getAbsolutePath() + "/";
} else {
return null;
}
}
protected String getWallpaperDestinationPath() {
String configFolder = getResourceString(com.death2all110.blisspapers.R.string.config_wallpaper_sdcard_dl_location);
if (configFolder != null && !configFolder.isEmpty()) {
return new File(Environment.getExternalStorageDirectory(), configFolder)
.getAbsolutePath();
}
// couldn't find resource?
return null;
}
protected String getResourceString(int stringId) {
return getApplicationContext().getResources().getString(stringId);
}
public static String getResourceString(Context c, int id) {
return c.getResources().getString(id);
}
private class LoadWallpaperManifest extends
AsyncTask<Void, Boolean, ArrayList<WallpaperCategory>> {
#Override
protected ArrayList<WallpaperCategory> doInBackground(Void... v) {
try {
InputStream input = null;
if (USE_LOCAL_MANIFEST) {
input = getApplicationContext().getAssets().open(MANIFEST);
} else {
URL url = new URL(getResourceString(com.death2all110.blisspapers.R.string.config_wallpaper_manifest_url));
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a typical
// 0-100%
// progress bar
int fileLength = connection.getContentLength();
// download the file
input = new BufferedInputStream(url.openStream());
}
OutputStream output = getApplicationContext().openFileOutput(
MANIFEST, MODE_PRIVATE);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
// file finished downloading, parse it!
ManifestXmlParser parser = new ManifestXmlParser();
return parser.parse(new File(getApplicationContext().getFilesDir(), MANIFEST),
getApplicationContext());
} catch (Exception e) {
Log.d(TAG, "Exception!", e);
}
return null;
}
#Override
protected void onPostExecute(ArrayList<WallpaperCategory> result) {
categories = result;
if (categories != null)
loadPreviewFragment();
mLoadingDialog.cancel();
super.onPostExecute(result);
}
}
}
Menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/action_about"
android:icon="#drawable/ic_menu_info"
android:title="#string/action_about"
android:showAsAction="always">
</item>
</menu>
In your onCreate() method for your fragment, try adding this one line of code:
setHasOptionsMenu(true);
Android API reference: enter link description here
I had the same problem when implementing a menu from a fragment
To me you should keep only one reference to onCreateOptionsMenu() and onOptionsItemSelected(). Since the fragment is hosted inside the Activity, it's enough to manage options menu from there. So:
Delete all instances of onCreateOptionsMenu() and onOptionsItemSelected() from your fragment;
Delete all instances of setHasOptionsMenu(true) you previously added;
In your Activity, just keep:
#Override
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
...
Note that in your code #Override is missing here and there.
That said, why are onCreateOptionsMenu() and onOptionsItemSelected() methods also available for fragments? Because if you have multiple fragments that can be shown in the same Activity, you might want to have each fragment add some items to the Activity OptionsMenu.
That is done with setHasOptionsMenu(true) and there are a lot of questions already answered here on the topic. But, as per what you said, that's not your case. You just want an Activity menu, so forget about the fragment.
The menu disappearing was you calling menu.clear().
Got it figured out.
I removed
Toolbar ab = (Toolbar) findViewById(R.id.toolbar);
setActionBar(ab);
from the loadPreviewFragment()
Then removed the Toolbar view from my activity_wallpaper.xml layout
And changed the parent theme in my style.xml from
parent=Theme.Material.NoActionBar
to
parent=Theme.Material
Thanks for the help guys.

Null Pointer Exception after some code moved to a custom Application class

Getting NullPointerException after I moved some of the code to a separate, custom application class called YambaApplication. This application posts to a Twitter enabled service. I checked the code 3 times, and cleaned the project 5 times:
Exception:
06-16 14:08:22.723: E/AndroidRuntime(392): Caused by:
java.lang.NullPointerException 06-16 14:08:22.723:
E/AndroidRuntime(392): at
com.user.yamba.StatusActivity$PostToTwitter.doInBackground(StatusActivity.java:70)
YambaApplication.java (here we initialize and return a twitter object):
package com.user.yamba;
import winterwell.jtwitter.Twitter;
import android.app.Application;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
public class YambaApplication extends Application implements
OnSharedPreferenceChangeListener {
private static final String TAG = YambaApplication.class.getSimpleName();
public Twitter twitter;
private SharedPreferences prefs;
#Override
public void onCreate() {
super.onCreate();
this.prefs = PreferenceManager.getDefaultSharedPreferences(this);
this.prefs.registerOnSharedPreferenceChangeListener(this);
Log.i(TAG, "onCreated");
}
#Override
public void onTerminate() {
super.onTerminate();
Log.i(TAG, "onTerminated");
}
#Override
public synchronized void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {
this.twitter = null;
}
public synchronized Twitter getTwitter() {
if (this.twitter == null) {
String username, password, apiRoot;
username = this.prefs.getString("username", "");
password = this.prefs.getString("password", "");
apiRoot = this.prefs.getString("apiRoot",
"http://yamba.marakana.com/api");
if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(password)
&& !TextUtils.isEmpty(apiRoot)) {
this.twitter = new Twitter(username, password);
this.twitter.setAPIRootUrl(apiRoot);
}
}
return this.twitter;
}
}
StatusActivity.java (the first activity user sees with an EditText and an update button. Most of the code from YambaApplication class was inside this class.):
package com.user.yamba;
import winterwell.jtwitter.Twitter;
import winterwell.jtwitter.TwitterException;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class StatusActivity extends Activity implements OnClickListener,
TextWatcher {
private static final String TAG = "StatusActivity";
EditText editTextStatusUpdate;
Button buttonStatusUpdate;
TextView textViewCharacterCounter;
//SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_status);
// Find views
editTextStatusUpdate = (EditText) findViewById(R.id.editStatus);
buttonStatusUpdate = (Button) findViewById(R.id.buttonUpdate);
buttonStatusUpdate.setOnClickListener(this);
textViewCharacterCounter = (TextView) findViewById(R.id.editTextUpdateStatusCounter);
textViewCharacterCounter.setText(Integer.toString(140));
textViewCharacterCounter.setTextColor(Color.GREEN);
editTextStatusUpdate.addTextChangedListener(this);
//prefs = PreferenceManager.getDefaultSharedPreferences(this);
//prefs.registerOnSharedPreferenceChangeListener(this);
// Initialize twitter
// twitter = new Twitter("student", "password");
// twitter.setAPIRootUrl("http://yamba.marakana.com/api");
}
#Override
public void onClick(View v) {
String statusUpdate = editTextStatusUpdate.getText().toString();
new PostToTwitter().execute(statusUpdate);
Log.d(TAG, "onClicked");
}
// Async class to post of twitter
class PostToTwitter extends AsyncTask<String, Integer, String> {
// Async post status to twitter
#Override
protected String doInBackground(String... params) {
try {
YambaApplication yamba = ((YambaApplication) getApplication());
Twitter.Status status = yamba.getTwitter().updateStatus(params[0]); // EXCEPTION FIRED HERE
return status.text;
} catch (TwitterException e) {
Log.e(TAG, "Failed to connect to twitter service");
return "Failed to post";
}
}
// Called when there's status to be updated
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
// Not used
}
// Called once async task completed
#Override
protected void onPostExecute(String result) {
Toast.makeText(StatusActivity.this, result, Toast.LENGTH_LONG)
.show();
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// Not in use
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Not in use
}
// Update characters counter after text
// is changed(entered or deleted)
#Override
public void afterTextChanged(Editable statusText) {
int count = 140 - statusText.length();
textViewCharacterCounter.setText(Integer.toString(count));
textViewCharacterCounter.setTextColor(Color.GREEN);
if (count < 10) {
textViewCharacterCounter.setTextColor(Color.YELLOW);
}
if (count < 0) {
textViewCharacterCounter.setTextColor(Color.RED);
}
}
// When user taps on the menu hardware button inflate
// the menu resource
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
// Determine what item user tapped on the menu
// and start the item's activity
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.itemPrefs:
startActivity(new Intent(this, PrefsActivity.class));
break;
}
return true;
}
// private Twitter getTwitter() {
// if (twitter == null) {
// String username, password, apiRoot;
// username = prefs.getString("username", "");
// password = prefs.getString("password", "");
// apiRoot = prefs.getString("apiRoot",
// "http://yamba.marakana.com/api");
//
// // Connect to twitter
// twitter = new Twitter(username, password);
// twitter.setAPIRootUrl(apiRoot);
// }
// return twitter;
// }
// #Override
// public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
// String key) {
// // invalidate twitter
// twitter = null;
//
// }
}
Manifest (added this line to the application tag in the manifest):
android:name=".YambaApplication"
The first thing I saw were the new checks for the username and password to contain text.
Maybe try to debug if they both are set correctly and if a Twitter Object is returned from the Application, or simply null, because of those checks.
Null is because in YambaApplication you check:
if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(password)
&& !TextUtils.isEmpty(apiRoot)) {
...
}
If any field is empty you get twiter == null.

Linkedin Integration Android [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am building an Android application which requires LinkedIn integration.The main job of application will be Login via native app and saving of LinkedIn access token.
I went through online projects, most of them were using external libraries.
How can i get LinkedIn access token using LinkedIn android library only and using simple Java class
?
Hope this code helps you out...this consist of all functionality that one can do with linkedin api:)
package com.mypackage.linkedin;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory.Options;
import android.net.Uri;
import android.net.http.SslError;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.provider.ContactsContract.Profile;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.code.linkedinapi.client.LinkedInApiClient;
import com.google.code.linkedinapi.client.LinkedInApiClientException;
import com.google.code.linkedinapi.client.LinkedInApiClientFactory;
import com.google.code.linkedinapi.client.LinkedInAuthenticationClient;
import com.google.code.linkedinapi.client.enumeration.NetworkUpdateType;
import com.google.code.linkedinapi.client.enumeration.ProfileField;
import com.google.code.linkedinapi.client.oauth.LinkedInAccessToken;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthService;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthServiceFactory;
import com.google.code.linkedinapi.client.oauth.LinkedInRequestToken;
import com.google.code.linkedinapi.schema.Connections;
import com.google.code.linkedinapi.schema.Network;
import com.google.code.linkedinapi.schema.NetworkStats;
import com.google.code.linkedinapi.schema.Person;
import com.google.code.linkedinapi.schema.Updates;
import com.mypackage.R;
import com.mypackage.account.Account;
import com.mypackage.account.AccountManagerClass;
import com.mypackage.fragment.SyncContactsFragment;
import com.mypackage.imageloader.ImageLoader;
import com.mypackage.user.User;
import com.mypackage.utils.PreferncesManagerClass;
import com.mypackage.utils.Utility;
import com.mypackage.widgets.CustomPopUpSocialMedia;
import com.mypackage.widgets.CustomToast;
/**
* #author harshalb
*This is main class of linkedin.
*/
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public class LinkedinWebviewDialog {
private Context mContext;
private WebView mWebView;
private final String TAG = "LinkedinWebviewDialog";
private static final EnumSet<ProfileField> ProfileParameters = EnumSet.allOf(ProfileField.class);
private final LinkedInOAuthService oAuthService =
LinkedInOAuthServiceFactory.getInstance().createLinkedInOAuthService(Config.LINKEDIN_KEY, Config.LINKED_SECRET);
private final LinkedInApiClientFactory factory =
LinkedInApiClientFactory.newInstance(Config.LINKEDIN_KEY, Config.LINKED_SECRET);
public LinkedInRequestToken linkedinToken;
public LinkedInApiClient linkedinClient;
private String callFrom="";
public final static String SYNC_FRIENDS="SYNC_FRIENDS",SHARE_STATUS="SHARE_STATUS";
private String statusText="";
/**
* #param context
* #param callFrom
*/
public LinkedinWebviewDialog(Context context, String callFrom) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
this.mContext=context;
this.callFrom=callFrom;
operations();
}
/**
* #param context
* #param callFrom
* #param shareStatus
*/
public LinkedinWebviewDialog(Context context, String callFrom, String shareStatus) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
this.mContext=context;
this.callFrom=callFrom;
this.statusText=shareStatus;
operations();
}
/**
* This method is used for using share preference.
*/
protected void operations() {
final SharedPreferences pref = mContext.getSharedPreferences(Config.OAUTH_PREF, Context.MODE_PRIVATE);
final String token = pref.getString(Config.PREF_TOKEN, null);
final String tokenSecret = pref.getString(Config.PREF_TOKENSECRET, null);
fetchInfo(token, tokenSecret);
}
/**
* This method is used for access token and webview dialog show.
*/
void authenticationStart() {
if(Utility.isConnected(mContext)==true)
{
final LinkedInRequestToken liToken = oAuthService.getOAuthRequestToken(Config.OAUTH_CALLBACK_URL);
final String url = liToken.getAuthorizationUrl();
mContext.getSharedPreferences(Config.OAUTH_PREF, Context.MODE_PRIVATE)
.edit()
.putString(Config.PREF_REQTOKENSECRET, liToken.getTokenSecret())
.commit();
WebviewDialog webviewDialog=new WebviewDialog(mContext,url);
webviewDialog.show();
}
else
{
CustomToast.makeText(mContext,"No Internet Connection",CustomToast.LENGTH_SHORT).show();
}
}
/**
* #param token
* #param tokenSecret
* This method is used for verification of tokens.
*/
private void fetchInfo(String token, String tokenSecret) {
if (token == null || tokenSecret == null) {
authenticationStart();
} else {
new AsyncGetCurrentUserInfo().execute(new LinkedInAccessToken(token, tokenSecret));
}
}
/**
* #param uri
* This method is used for access token and asyn task execution.
*/
void authenticationFinish(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) {
final SharedPreferences pref = mContext.getSharedPreferences(Config.OAUTH_PREF, Context.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();
new AsyncGetCurrentUserInfo().execute(accessToken);
} else {
}
}else{
//error
}
}
/**
* #author harshalb
*
*This is asyntask for linkedin.
*/
class AsyncGetCurrentUserInfo extends AsyncTask<LinkedInAccessToken, Integer, Person> {
ProgressDialog dialog;
private LinkedInAccessToken accessToken;
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(mContext);
dialog.setMessage("Please wait...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
#Override
protected Person doInBackground(LinkedInAccessToken... arg0) {
try{
accessToken=arg0[0];
linkedinClient = factory.createLinkedInApiClient(accessToken);
// networkUpdatesApiClient = factory.createNetworkUpdatesApiClient(accessToken);
// networkUpdatesApiClient.setAccessToken(accessToken);
linkedinClient.setAccessToken(accessToken);
return linkedinClient.getProfileForCurrentUser(ProfileParameters);
} catch (LinkedInApiClientException ex){
Log.e(TAG, "LinkedInApiClientException: ", ex);
return null;
}
}
#Override
protected void onPostExecute(Person person) {
if(person == null){
CustomToast.makeText(mContext,"application_down_due_to_linkedinapiclientexception", CustomToast.LENGTH_SHORT).show();
dialog.dismiss();
}else{
System.out.println("person info :");
System.out.println("person name"+person.getFirstName() +" "+person.getLastName());
// mCurrentPerson = person;
// populateAll(person);
/*SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(mContext);
Editor editor = sharedPreferences.edit();
editor.putString("sync_linkedin_data","Your account synced with: "+person.getFirstName()+" "+person.getLastName());
editor.commit();*/
PreferncesManagerClass preferncesManagerClass=new PreferncesManagerClass(mContext);
preferncesManagerClass.addLinkedInData("Your account synced with: "+person.getFirstName()+" "+person.getLastName());
System.out.println("hello name:"+person.getFirstName());
if(callFrom.equalsIgnoreCase(SHARE_STATUS)){
new AsyncTask<String, String, String>() {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog=new ProgressDialog(mContext);
}
#Override
protected String doInBackground(String... params) {
try {
Person person = linkedinClient.getProfileForCurrentUser(EnumSet
.of(ProfileField.FIRST_NAME,
ProfileField.LAST_NAME,
ProfileField.PICTURE_URL));
// String fullName=person.getFirstName()+" "+person.getLastName();
String urlMyappsco="www.myappsco.com";
AccountManagerClass accountManagerClass=new AccountManagerClass();
Account account=accountManagerClass.getAccountInfo(mContext);
linkedinClient.updateCurrentStatus(urlMyappsco+" "+account.rank+"(Id #"+accountManagerClass.getAboId(mContext)+")"+" "+mContext.getResources().getString(R.string.abo_url)+account.userName);
// linkedinClient.updateCurrentStatus("Promoter (Id #"+accountManagerClass.getAboId(mContext)+")"+" "+accountManagerClass.getAccountInfo(mContext).aboDescription);
// linkedinClient.updateCurrentStatus("This is Myappsco website1:"+"www.myappsco.com");
// linkedinClient.postNetworkUpdate("This is Myappsco website2:"+"www.myappsco.com");
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
System.out.println("throttle::"+e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result) {
CustomToast.makeText(mContext,"Posted successfully", CustomToast.LENGTH_SHORT).show();
super.onPostExecute(result);
}
}.execute("");
}else if (callFrom.equalsIgnoreCase(SYNC_FRIENDS)) {
LinkedInFriends friends=new LinkedInFriends(mContext,accessToken);
friends.show();
}
dialog.dismiss();
}
}
}
/**
* List of listener.
*/
private List<OnVerifyListener> listeners = new ArrayList<OnVerifyListener>();
/**
* Register a callback to be invoked when authentication have finished.
*
* #param data
* The callback that will run
*/
public void setVerifierListener(OnVerifyListener data) {
listeners.add(data);
}
/**
*
*/
public void doOprations() {
if(callFrom.equalsIgnoreCase(SYNC_FRIENDS)){
setVerifierListener(new OnVerifyListener() {
#Override
public void onVerify(String verifier) {
try {
Log.i("LinkedinSample", "verifier: " + verifier);
LinkedInAccessToken accessToken = oAuthService.getOAuthAccessToken(linkedinToken,
verifier);
linkedinClient = factory.createLinkedInApiClient(accessToken);
LinkedInFriends linkedInFriends=new LinkedInFriends(mContext,accessToken);
linkedInFriends.show();
}catch (Exception e) {
// TODO: handle exception
}
}
});
}else if(callFrom.equalsIgnoreCase(SHARE_STATUS)){
setVerifierListener(new OnVerifyListener() {
#Override
public void onVerify(String verifier) {
try {
Log.i("LinkedinSample", "verifier: " + verifier);
LinkedInAccessToken accessToken = oAuthService.getOAuthAccessToken(linkedinToken,
verifier);
linkedinClient = factory.createLinkedInApiClient(accessToken);
// linkedinClient.updateCurrentStatus(status);
// currentStatus.setText("");
linkedinClient.postNetworkUpdate(statusText);
Person profile = linkedinClient.getProfileForCurrentUser(EnumSet
.of(ProfileField.FIRST_NAME,
ProfileField.LAST_NAME,
ProfileField.PICTURE_URL));
Log.e("Name:",
"" + profile.getFirstName() + " "
+ profile.getLastName());
Log.e("Headline:", "" + profile.getHeadline());
Log.e("Summary:", "" + profile.getSummary());
Log.e("Industry:", "" + profile.getIndustry());
Log.e("Picture url:", "" + profile.getPictureUrl());
String stringUrl = profile.getPictureUrl().toString();
System.out.println("url test" + stringUrl);
Connections connections =linkedinClient.getConnectionsForCurrentUser();
List<String> list = new ArrayList<String>();
for(Person p :connections.getPersonList()) {
Log.e("Name", "" + p.getLastName() + " " +p.getFirstName());
Log.e("Industry ", "" + p.getIndustry());
Log.e(" ", "" + "*****************");
Log.e("currentStatus ",""+p.getCurrentStatus());
Log.e("link ",""+p.getPublicProfileUrl());
Log.e("position ",""+p.getEducations());
Log.e("id","" +p.getId());
list.add(p.getId());
}
System.out.println("list::"+list);
} catch (Exception e) {
e.printStackTrace();
}
}
});
// LinkedinWebviewDialog.this.dismiss();
}
}
/**
* Listener for oauth_verifier.
*/
public interface OnVerifyListener {
/**
* invoked when authentication have finished.
*
* #param verifier
* oauth_verifier code.
*/
public void onVerify(String verifier);
}
/**
* #author harshalb
*This class is used for firends and message.
*/
public class LinkedInFriends extends Dialog{
//Activity activity;
LayoutInflater inflater;
ListView listViewFriends;
List<Person> arraylistFriends;
Connections connections;
ImageLoader imageLoader;
LinkedInFriendsAdapter linkedInFriendsAdapter;
private Context context;
public LinkedInFriends(Context context, LinkedInAccessToken arg0) {
super(context);
this.context=context;
linkedinClient = factory.createLinkedInApiClient(arg0);
linkedinClient.setAccessToken(arg0);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// activity=getOwnerActivity();
setContentView(R.layout.friends_dialog_main);
listViewFriends=(ListView)findViewById(R.id.listview_friends);
arraylistFriends=new ArrayList<Person>();
connections = linkedinClient.getConnectionsForCurrentUser();
arraylistFriends=connections.getPersonList();
setAdapter();
}
public void setAdapter() {
linkedInFriendsAdapter=new LinkedInFriendsAdapter(arraylistFriends);
listViewFriends.setAdapter(linkedInFriendsAdapter);
listViewFriends.setOnItemClickListener(linkedInFriendsAdapter);
}
/**
* #author harshalb
*This class is adapter class used for friends.
*/
public class LinkedInFriendsAdapter extends BaseAdapter implements OnItemClickListener{
List<Person> arrayList;
public LinkedInFriendsAdapter(List<Person> arraylistFriends) {
// TODO Auto-generated constructor stub
arrayList=arraylistFriends;
inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrayList.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arrayList.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
/**
* #author harshalb
*This is holder class.
*/
class ViewHolder
{
ImageView friendImage;
TextView friendText;
Button friendSendMessage;
}
/**
* #author harshalb
*This class is used for sending message from dialog list.
*/
class SendMessageOnClick implements android.view.View.OnClickListener{
int position;
SendMessageOnClick(int position){
this.position=position;
}
#Override
public void onClick(View v) {
dismiss();
System.out.println("send message click..."+position);
Person p=(Person) v.getTag();
String idValue =p.getId();
System.out.println("id array list" +Arrays.asList(idValue));
final CustomPopUpSocialMedia customPopUpSocialMedia = new CustomPopUpSocialMedia(context,"Message");
customPopUpSocialMedia.setEditText();
customPopUpSocialMedia.setSocialMediaTitle("Visit MyAppsCo");
customPopUpSocialMedia.setSocialMediaMessage("Message");
customPopUpSocialMedia.setSocialMediaUsername(p.getFirstName()+" "+p.getLastName());
String storeUrl=mContext.getResources().getString(R.string.abo_url);
AccountManagerClass accountManagerClass=new AccountManagerClass();
final Account account=accountManagerClass.getAccountInfo(mContext);
customPopUpSocialMedia.setSocialMediaUrl("Visit my MyAppsCo App Store at"+" "+storeUrl+account.userName);
customPopUpSocialMedia.setFirstButton("OK");
customPopUpSocialMedia.mFirstButton.setTag(p);
customPopUpSocialMedia.setFirstButtonOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String shareStatus=customPopUpSocialMedia.getEditText();
System.out.println("shareStatus ok"+shareStatus);
System.out.println("DoneOnClick... ok"+position);
Person p=(Person) v.getTag();
String idValue =p.getId();
System.out.println("DoneOnClick...id array list" +Arrays.asList(idValue));
// linkedinClient.sendMessage(Collections.addAll(arrayList, person.getId()), "HARSHAL BENAKE DEMO", "my app demo HELLO");
try
{
String linkAppStore=mContext.getResources().getString(R.string.abo_url);
linkedinClient.sendMessage(Arrays.asList(idValue),"Visit MyAppsCo-Abo",p.getFirstName()+" "+p.getLastName()+System.getProperty("line.separator")+shareStatus+System.getProperty("line.separator")+"Visit my MyAppsCo App Store at"+" "+linkAppStore+account.userName);
//linkedinClient.sendMessage(Arrays.asList(idValue),"Visit MyAppsCo-Abo",account.fullName+System.getProperty("line.separator")+visitAppStore+" "+linkAppStore+accountManagerClass.getAboId(mContext)+".html"+" "+System.getProperty("line.separator")+"Visit at"+" "+urlMyappsco+" "+"site");
CustomToast.makeText(mContext,"Sent message successfully", CustomToast.LENGTH_SHORT).show();
}
catch (Exception e) {
// TODO: handle exception
System.out.println("throttle::"+e);
CustomToast.makeText(mContext,"Throttle limit for calls to this resource is reached", CustomToast.LENGTH_SHORT).show();
}
customPopUpSocialMedia.dismiss();
}
});
customPopUpSocialMedia.show();
}
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
// TODO Auto-generated method stub
Person person = arrayList.get(position);
//arrayList = arrayList.get(position);
ViewHolder viewHolder;
if(view==null){
view=inflater.inflate(R.layout.friends_list, null);
viewHolder=new ViewHolder();
viewHolder.friendImage=(ImageView)view.findViewById(R.id.friend_image);
viewHolder.friendText=(TextView)view.findViewById(R.id.friend_text);
viewHolder.friendSendMessage=(Button)view.findViewById(R.id.friend_sendmessage);
viewHolder.friendSendMessage.setOnClickListener(new SendMessageOnClick(position));
view.setTag(viewHolder);
}
else{
viewHolder=(ViewHolder)view.getTag();
}
viewHolder.friendText.setText(person.getFirstName());
imageLoader=new ImageLoader(context,person.getPictureUrl());
imageLoader.displayImage(person.getPictureUrl(), viewHolder.friendImage, false);
viewHolder.friendSendMessage.setTag(person);
// imageLoader.bind(viewHolder.friendImage, person.getPictureUrl(), callback);
return view;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
arrayList.get(arg2);
}
}
}
/**
* #author harshalb
*This class is main webview dialog.
*/
class WebviewDialog extends Dialog {
private Context mContext;
private String mUrl;
/**
* #param context
* #param url
*/
public WebviewDialog(Context context, String url) {
super(context);
this.mContext=context;
this.mUrl=url;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);// must call before super.
super.onCreate(savedInstanceState);
setContentView(R.layout.linkedin_webview);
setWebView(mUrl);
}
/**
* set webview.
* #param url
*/
#SuppressLint({ "SetJavaScriptEnabled", "NewApi" })
public void setWebView(String url) {
mWebView = (WebView) findViewById(R.id.linkedin_webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setAppCacheEnabled(true);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.loadUrl(url);
mWebView.setWebViewClient(new LinkedInWebViewClient());
}
/**
* #author harshalb
*This class is webview client.
*/
class LinkedInWebViewClient extends WebViewClient {
ProgressDialog dialog;
LinkedInWebViewClient(){
dialog=new ProgressDialog(mContext);
dialog.setMessage("Please wait...");
dialog.setCancelable(false);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
dialog.show();
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if(dialog!=null && dialog.isShowing())
dialog.dismiss();
System.out.println("onPageFinished URL :"+url);
authenticationFinish(Uri.parse(url));
// doOprations();
}
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
if(dialog!=null && dialog.isShowing())
dialog.dismiss();
System.out.println("onReceivedError errorCode :"+errorCode +" description : "+description);
System.out.println("onReceivedError failingUrl :"+failingUrl);
super.onReceivedError(view, errorCode, description, failingUrl);
}
#Override
public void onReceivedSslError(WebView view, SslErrorHandler handler,
SslError error) {
if(dialog!=null && dialog.isShowing())
dialog.dismiss();
System.out.println("onReceivedSslError error :"+error.getPrimaryError());
super.onReceivedSslError(view, handler, error);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains(Config.OAUTH_CALLBACK_URL)) {
Uri uri = Uri.parse(url);
String verifier = uri.getQueryParameter("oauth_verifier");
for (OnVerifyListener d : listeners) {
// call listener method
d.onVerify(verifier);
}
cancel();
} else if (url
.contains("www.mypackage.com")) {
cancel();
} else {
Log.i("LinkedinSample", "url: " + url);
view.loadUrl(url);
}
return true;
}
}
}
}

Categories

Resources