问:
Android throwing up Error using jtwitter
I am trying to write a twitter application on Android target 2.2 (using some sample code that I found on the net and using Marko Gargenta's O'Reilly text). I am stuck with the problem as in the log below. The source code is given first followed by the log. Any idea what's going wrong here ? Also does anyone have or can point to a sample jtwitter code working on Android.

Thanks,
Ravi

```<code>protected String doInBackground(String... statuses) {
  try {

         //Autho information
         /*OAuthSignpostClient oauthclient = new OAuthSignpostClient(cons_key,
           cons_secret, access_token, access_secret);*/

         OAuthSignpostClient oauthclient = new OAuthSignpostClient(access_token, access_secret,"oob");

         //***POSTING TO TWITTER CURRENTLY DOES NOT WORK WITH THIS INTERFACE
         twitter = new Twitter(mytwitterusername, oauthclient);
         //twitter.setAPIRootUrl("http://learningandroid.status.net/api");

   //***POSTING TO TWITTER CURRENTLY DOES NOT WORK WITH THIS INTERFACE
   Log.i(Logtag, "Status currently is " + statuses[0]);

   Twitter.Status status = twitter.updateStatus(statuses[0]);
   //return status.text;
   return statuses[0];
  } catch (TwitterException e) {
   Log.e(Logtag, e.toString());
   e.printStackTrace();
   return "Failed to post to Twitter";
  }
</code>```

}

Log file:

```<code>E/dalvikvm(  719): Could not find method javax.swing.JOptionPane.showInputDialog, referenced from method winterwell.jtwi
tter.OAuthSignpostClient.askUser
W/dalvikvm(  719): VFY: unable to resolve static method 443: Ljavax/swing/JOptionPane;.showInputDialog (Ljava/lang/Objec
t;)Ljava/lang/String;
W/dalvikvm(  719): VFY:  rejecting opcode 0x71 at 0x0000
W/dalvikvm(  719): VFY:  rejected Lwinterwell/jtwitter/OAuthSignpostClient;.askUser (Ljava/lang/String;)Ljava/lang/Strin
g;
W/dalvikvm(  719): Verifier rejected class Lwinterwell/jtwitter/OAuthSignpostClient;
W/dalvikvm(  719): threadid=17: thread exiting with uncaught exception (group=0x4000fe70)
E/AndroidRuntime(  719): Uncaught handler: thread AsyncTask #1 exiting due to uncaught exception
E/AndroidRuntime(  719): java.lang.RuntimeException: An error occured while executing doInBackground()
E/AndroidRuntime(  719):        at android.os.AsyncTask$3.done(AsyncTask.java:200)
E/AndroidRuntime(  719):        at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:234)
E/AndroidRuntime(  719):        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:258)
E/AndroidRuntime(  719):        at java.util.concurrent.FutureTask.run(FutureTask.java:122)
E/AndroidRuntime(  719):        at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:648)
E/AndroidRuntime(  719):        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:673)
E/AndroidRuntime(  719):        at java.lang.Thread.run(Thread.java:1058)
E/AndroidRuntime(  719): Caused by: java.lang.VerifyError: winterwell.jtwitter.OAuthSignpostClient
E/AndroidRuntime(  719):        at com.ravi.tweeto.StatusActivity$PostToTwitter.doInBackground(StatusActivity.java:81)
E/AndroidRuntime(  719):        at com.ravi.tweeto.StatusActivity$PostToTwitter.doInBackground(StatusActivity.java:1)
E/AndroidRuntime(  719):        at android.os.AsyncTask$2.call(AsyncTask.java:185)
E/AndroidRuntime(  719):        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:256)
E/AndroidRuntime(  719):        ... 4 more
I/Process (  585): Sending signal. PID: 719 SIG: 3
I/dalvikvm(  719): threadid=7: reacting to signal 3
I/dalvikvm(  719): Wrote stack trace to '/data/anr/traces.txt'
----
</code>```

答:
I found most of the code I use somewhere on GitHub (can't find the exact link right now)
A few searches on snippets of the code send me here, but I don't think that was the exact site I got it from.

But this is what I have in my semi-working code.

OAUTH.java

```<code>import junit.framework.Assert;
import oauth.signpost.OAuth;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.exception.OAuthNotAuthorizedException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;

public class OAUTH extends Activity {
private static final String TAG = "OAUTH";

public static final String USER_TOKEN = "user_token";
public static final String USER_SECRET = "user_secret";
public static final String REQUEST_TOKEN = "request_token";
public static final String REQUEST_SECRET = "request_secret";

public static final String TWITTER_REQUEST_TOKEN_URL = "http://twitter.com/oauth/request_token";
public static final String TWITTER_ACCESS_TOKEN_URL = "http://twitter.com/oauth/access_token";
public static final String TWITTER_AUTHORIZE_URL = "http://twitter.com/oauth/authorize";

private static final Uri CALLBACK_URI = Uri.parse("gpsagenda://twitt");

public static final String PREFS = "MyPrefsFile";

private OAuthConsumer mConsumer = null;
private OAuthProvider mProvider = null;

SharedPreferences mSettings;

public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    // We don't need to worry about any saved states: we can reconstruct the state
    mConsumer = new CommonsHttpOAuthConsumer(
            "myKey",
            "mySecret");

    mProvider = new CommonsHttpOAuthProvider (
            TWITTER_REQUEST_TOKEN_URL,
            TWITTER_ACCESS_TOKEN_URL,
            TWITTER_AUTHORIZE_URL);

    // It turns out this was the missing thing to making standard Activity launch mode work
    mProvider.setOAuth10a(true);

    mSettings = this.getSharedPreferences(PREFS, Context.MODE_PRIVATE);

    Intent i = this.getIntent();
    if (i.getData() == null) {
        try {
                            // This is really important. If you were able to register your real callback Uri with Twitter, and not some fake Uri
                            // like I registered when I wrote this example, you need to send null as the callback Uri in this function call. Then
                            // Twitter will correctly process your callback redirection
            String authUrl = mProvider.retrieveRequestToken(mConsumer, CALLBACK_URI.toString());
            saveRequestInformation(mSettings, mConsumer.getToken(), mConsumer.getTokenSecret());
            this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
        } catch (OAuthMessageSignerException e) {
            e.printStackTrace();
        } catch (OAuthNotAuthorizedException e) {
            e.printStackTrace();
        } catch (OAuthExpectationFailedException e) {
            e.printStackTrace();
        } catch (OAuthCommunicationException e) {
            e.printStackTrace();
        }
    }
}

@Override
protected void onResume() {
    super.onResume();

    Uri uri = getIntent().getData();
    if (uri != null && CALLBACK_URI.getScheme().equals(uri.getScheme())) {
        String token = mSettings.getString(OAUTH.REQUEST_TOKEN, null);
        String secret = mSettings.getString(OAUTH.REQUEST_SECRET, null);
        Intent i = new Intent(this, DetailsContainer.class); // Currently, how we get back to main activity.

        try {
            if(!(token == null || secret == null)) {
                mConsumer.setTokenWithSecret(token, secret);
            }
            String otoken = uri.getQueryParameter(OAuth.OAUTH_TOKEN);
            String verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);

            // We send out and save the request token, but the secret is not the same as the verifier
            // Apparently, the verifier is decoded to get the secret, which is then compared - crafty
            // This is a sanity check which should never fail - hence the assertion
            Assert.assertEquals(otoken, mConsumer.getToken());

            // This is the moment of truth - we could throw here
            mProvider.retrieveAccessToken(mConsumer, verifier);
            // Now we can retrieve the goodies
            token = mConsumer.getToken();
            secret = mConsumer.getTokenSecret();
            OAUTH.saveAuthInformation(mSettings, token, secret);
            // Clear the request stuff, now that we have the real thing
            OAUTH.saveRequestInformation(mSettings, null, null);
            i.putExtra(USER_TOKEN, token);
            i.putExtra(USER_SECRET, secret);
        } catch (OAuthMessageSignerException e) {
            e.printStackTrace();
        } catch (OAuthNotAuthorizedException e) {
            e.printStackTrace();
        } catch (OAuthExpectationFailedException e) {
            e.printStackTrace();
        } catch (OAuthCommunicationException e) {
            e.printStackTrace();
        } finally {
            startActivity(i); // we either authenticated and have the extras or not, but we're going back
            finish();
        }
    }
}

public static void saveRequestInformation(SharedPreferences settings, String token, String secret) {
    // null means to clear the old values
    SharedPreferences.Editor editor = settings.edit();
    if(token == null) {
        editor.remove(OAUTH.REQUEST_TOKEN);
        Log.d(TAG, "Clearing Request Token");
    }
    else {
        editor.putString(OAUTH.REQUEST_TOKEN, token);
        Log.d(TAG, "Saving Request Token: " + token);
    }
    if (secret == null) {
        editor.remove(OAUTH.REQUEST_SECRET);
        Log.d(TAG, "Clearing Request Secret");
    }
    else {
        editor.putString(OAUTH.REQUEST_SECRET, secret);
        Log.d(TAG, "Saving Request Secret: " + secret);
    }
    editor.commit();

}

public static void saveAuthInformation(SharedPreferences settings, String token, String secret) {
    // null means to clear the old values
    SharedPreferences.Editor editor = settings.edit();
    if(token == null) {
        editor.remove(OAUTH.USER_TOKEN);
        Log.d(TAG, "Clearing OAuth Token");
    }
    else {
        editor.putString(OAUTH.USER_TOKEN, token);
        Log.d(TAG, "Saving OAuth Token: " + token);
    }
    if (secret == null) {
        editor.remove(OAUTH.USER_SECRET);
        Log.d(TAG, "Clearing OAuth Secret");
    }
    else {
        editor.putString(OAUTH.USER_SECRET, secret);
        Log.d(TAG, "Saving OAuth Secret: " + secret);
    }
    editor.commit();

}

}
</code>```

DetailsTwitter.java (my "implementation")

```<code>import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.LinkedList;

import oauth.signpost.OAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;

import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.gpsagenda.OAUTH;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class DetailsTwitter extends Activity {

    public SharedPreferences mSettings;

    private LinkedList<UserStatus> mHomeStatus = new LinkedList<UserStatus>();
    public String mToken;
    public String mSecret;
    private OAuthConsumer mConsumer = null;
    private HttpClient mClient;
    private EditText mEditor;
    private TextView mLast;
    private CheckBox mCB;
    private Button mButton;
    private TextView mUser;
    private int ID;

    public static final String VERIFY_URL_STRING = "http://twitter.com/account/verify_credentials.json";
    public static final String PUBLIC_TIMELINE_URL_STRING = "http://twitter.com/statuses/public_timeline.json";
    public static final String USER_TIMELINE_URL_STRING = "http://twitter.com/statuses/user_timeline.json";
    public static final String HOME_TIMELINE_URL_STRING = "http://api.twitter.com/1/statuses/home_timeline.json";
    public static final String FRIENDS_TIMELINE_URL_STRING = "http://api.twitter.com/1/statuses/friends_timeline.json";
    public static final String STATUSES_URL_STRING = "http://twitter.com/statuses/update.json";

    ProgressDialog postDialog = null;

    public static final String TWITTER_REQUEST_TOKEN_URL = "http://twitter.com/oauth/request_token";
    public static final String TWITTER_ACCESS_TOKEN_URL = "http://twitter.com/oauth/access_token";
    public static final String TWITTER_AUTHORIZE_URL = "http://twitter.com/oauth/authorize";

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.detailstwittertab);

        HttpParams parameters = new BasicHttpParams();
        HttpProtocolParams.setVersion(parameters, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(parameters, HTTP.DEFAULT_CONTENT_CHARSET);
        HttpProtocolParams.setUseExpectContinue(parameters, false);
        HttpConnectionParams.setTcpNoDelay(parameters, true);
        HttpConnectionParams.setSocketBufferSize(parameters, 8192);

        SchemeRegistry schReg = new SchemeRegistry();
        schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        ClientConnectionManager tsccm = new ThreadSafeClientConnManager(parameters, schReg);
        mClient = new DefaultHttpClient(tsccm, parameters);

        mCB = (CheckBox) this.findViewById(R.id.enable);
        mCB.setChecked(false);
        mEditor = (EditText) this.findViewById(R.id.editor);
        mButton = (Button) this.findViewById(R.id.post);
        mUser = (TextView) this.findViewById(R.id.user);
        mLast = (TextView) this.findViewById(R.id.last);

        mSettings = getSharedPreferences(OAUTH.PREFS, Context.MODE_PRIVATE);
        mConsumer = new CommonsHttpOAuthConsumer(
            "myKey",
            "mySecret");
    }

    public void PostTweet(View v) {
        String postString = mEditor.getText().toString();
        if (postString.length() == 0) {
            Toast.makeText(this, getText(R.string.tweet_empty), Toast.LENGTH_SHORT).show();
        } else {
            BitlyAndroid bitly = new BitlyAndroid("iarwain01", "R_1bffd0176aa731a27e5b2d23cf043199");
            String shortUrl = "";
            // Try to get the corresponding ID of the POI
           try
           {
               ID = getIntent().getExtras().getInt("id");
           } catch (NullPointerException e)
           {
               e.printStackTrace();
           }
            try {
                shortUrl = bitly.getShortUrl("http://gpsagenda.ikdoeict.be/projecten2/index.php?module=places&id=" + ID);
            } catch (Exception e) {
                Log.e("Debug", "Link shortening failed!");
                e.printStackTrace();
            }

            new PostTask().execute(postString + " " + shortUrl);
        }
    }

    protected void onFinish() {
        mClient.getConnectionManager().shutdown();
    }

    public void ConnectWithTwitter(View v)
    {
        if(mCB.isChecked()) {
            Intent i = new Intent(this, OAUTH.class);
            startActivity(i);
        } else {
            OAUTH.saveAuthInformation(mSettings, null, null);
            mButton.setEnabled(false);
            mEditor.setEnabled(false);
            mCB.setChecked(false);
            mUser.setText("");
        }
        mCB.setChecked(false); // the oauth callback will set it to the proper state
    }

    @Override
    public void onResume()
    {
        super.onResume();

        // We look for saved user keys
        if(mSettings.contains(OAUTH.USER_TOKEN) && mSettings.contains(OAUTH.USER_SECRET)) {
            mToken = mSettings.getString(OAUTH.USER_TOKEN, null);
            mSecret = mSettings.getString(OAUTH.USER_SECRET, null);
            if(!(mToken == null || mSecret == null)) {
                mConsumer.setTokenWithSecret(mToken, mSecret);
            }
        }
        new GetCredentialsTask().execute();
    }

    // These parameters are needed to talk to the messaging service
    public HttpParams getParams() {
        // Tweak further as needed for your app
        HttpParams params = new BasicHttpParams();
        // set this to false, or else you'll get an Expectation Failed: error
        HttpProtocolParams.setUseExpectContinue(params, false);

        return params;
    }

    //----------------------------
    // This task posts a message to your message queue on the service.
    private class PostTask extends AsyncTask<String, Void, JSONObject> {

        ProgressDialog postDialog;

        @Override
        protected void onPreExecute() {
            postDialog = ProgressDialog.show(DetailsTwitter.this,
                    getText(R.string.tweet_progress_title),
                    getText(R.string.tweet_progress_text),
                    true,   // indeterminate duration
                    false); // not cancel-able
        }

        @Override
        protected JSONObject doInBackground(String... params) {

            JSONObject jso = null;
            try {
                HttpPost post = new HttpPost("http://twitter.com/statuses/update.json");
                LinkedList<BasicNameValuePair> out = new LinkedList<BasicNameValuePair>();
                out.add(new BasicNameValuePair("status", params[0]));
                post.setEntity(new UrlEncodedFormEntity(out, HTTP.UTF_8));
                post.setParams(getParams());
                // sign the request to authenticate
                mConsumer.sign(post);
                String response = mClient.execute(post, new BasicResponseHandler());
                jso = new JSONObject(response);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (OAuthMessageSignerException e) {
                e.printStackTrace();
            } catch (OAuthExpectationFailedException e) {
                e.printStackTrace();
            } catch (OAuthCommunicationException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            } finally {

            }
            return jso;
        }

        // This is in the UI thread, so we can mess with the UI
        protected void onPostExecute(JSONObject jso) {
            postDialog.dismiss();
            if(jso != null) { // authorization succeeded, the json object contains the user information
                mEditor.setText("");
                mLast.setText(getCurrentTweet(jso));
            } else {
                mLast.setText(getText(R.string.tweet_error));
            }
        }
    }

    // Get stuff from the two types of Twitter JSONObject we deal with: credentials and status
    private String getCurrentTweet(JSONObject status) {
        return status.optString("text", getString(R.string.bad_value));
    }

    //----------------------------
    // This task is run on every onResume(), to make sure the current credentials are valid.
    // This is probably overkill for a non-educational program
    private class GetCredentialsTask extends AsyncTask<Void, Void, JSONObject> {

        ProgressDialog authDialog;

        @Override
        protected void onPreExecute() {
            authDialog = ProgressDialog.show(DetailsTwitter.this,
                getText(R.string.auth_progress_title),
                getText(R.string.auth_progress_text),
                true,   // indeterminate duration
                false); // not cancel-able
        }

        @Override
        protected JSONObject doInBackground(Void... arg0) {
            JSONObject jso = null;
            HttpGet get = new HttpGet(VERIFY_URL_STRING);
            try {
                mConsumer.sign(get);
                String response = mClient.execute(get, new BasicResponseHandler());
                jso = new JSONObject(response);
            } catch (OAuthMessageSignerException e) {
                e.printStackTrace();
            } catch (OAuthExpectationFailedException e) {
                e.printStackTrace();
            } catch (OAuthCommunicationException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return jso;
        }

        // This is in the UI thread, so we can mess with the UI
        protected void onPostExecute(JSONObject jso) {
            authDialog.dismiss();
            mCB.setChecked(jso != null);
            mButton.setEnabled(jso != null);
            mEditor.setEnabled(jso != null);
            mUser.setText(jso != null ? getUserName(jso) : getString(R.string.userhint));
            mLast.setText(jso != null ? getLastTweet(jso) : getString(R.string.userhint));
            if(jso != null) {
                TimelineSelector ss = new TimelineSelector(HOME_TIMELINE_URL_STRING);
                new GetTimelineTask().execute(ss);
            }
        }
    }

    private String getLastTweet(JSONObject credentials) {
        try {
            JSONObject status = credentials.getJSONObject("status");
            return getCurrentTweet(status);
        } catch (JSONException e) {
            e.printStackTrace();
            return getString(R.string.tweet_error);
        }
    }

    private String getUserName(JSONObject credentials) {
        return credentials.optString("name", getString(R.string.bad_value));
    }

    private class TimelineSelector extends Object {
        public String url; // the url to perform the query from
        // not all these apply to every url - you are responsible
        public Long since_id; // ids newer than this will be fetched
        public Long max_id; // ids older than this will be fetched
        public Integer count; // # of tweets to fetch Max is 200
        public Integer page; // # of page to fetch (with limits)

        public TimelineSelector(String u) {
            url = u;
            max_id = null;
            since_id = null;
            count = null;
            page = null;
        }

        @SuppressWarnings("unused")
        public TimelineSelector(String u, Long since, Long max, Integer cnt, Integer pg) {
            url = u;
            max_id = max;
            since_id = since;
            count = cnt;
            page = pg;
        }
    }

    private class UserStatus {

        JSONObject mStatus;
        @SuppressWarnings("unused")
        JSONObject mUser;

        public UserStatus(JSONObject status) throws JSONException {

            mStatus = status;
            mUser = status.getJSONObject("user");
        }
        @SuppressWarnings("unused")
        public long getId() {
            return mStatus.optLong("id", -1);
        }
        /*public String getUserName() {
            return mUser.optString("name", getString(R.string.bad_value));
        }
        public String getText() {
            return getCurrentTweet(mStatus);
        }
        public String getCreatedAt() {
            @SuppressWarnings("unused")
            Time ret1 = new Time();
            return mStatus.optString("created_at", getString(R.string.bad_value));
        }*/
    }

    private class GetTimelineTask extends AsyncTask<TimelineSelector, Void, JSONArray> {

        @Override
        protected JSONArray doInBackground(TimelineSelector... params) {
            JSONArray array = null;
            try {
                for(int i = 0; i < params.length; ++i) {
                    Uri sUri = Uri.parse(params[i].url);
                    Uri.Builder builder = sUri.buildUpon();
                    if(params[i].since_id != null) {
                        builder.appendQueryParameter("since_id", String.valueOf(params[i].since_id));
                    } else if (params[i].max_id != null) { // these are mutually exclusive
                        builder.appendQueryParameter("max_id", String.valueOf(params[i].max_id));
                    }
                    if(params[i].count != null) {
                        builder.appendQueryParameter("count", String.valueOf((params[i].count > 200) ? 200 : params[i].count));
                    }
                    if(params[i].page != null) {
                        builder.appendQueryParameter("page", String.valueOf(params[i].page));
                    }
                    HttpGet get = new HttpGet(builder.build().toString());
                    mConsumer.sign(get);
                    String response = mClient.execute(get, new BasicResponseHandler());
                    array = new JSONArray(response);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (OAuthMessageSignerException e) {
                e.printStackTrace();
            } catch (OAuthExpectationFailedException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (OAuthCommunicationException e) {
                e.printStackTrace();
            }
            return array;
        }

        // This is in the UI thread, so we can mess with the UI
        protected void onPostExecute(JSONArray array) {
            if(array != null) {
                try {
                    for(int i = 0; i < array.length(); ++i) {
                        JSONObject status = array.getJSONObject(i);
                        UserStatus s = new UserStatus(status);
                        mHomeStatus.add(s);
                    }
                    //mAA.notifyDataSetChanged();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
            }
        }
    }
}
</code>```

My AndroidManifest.xml

```<code>    <activity android:name="DetailsTwitter" />
    <activity android:name="OAUTH" >
        <intent-filter>
            <action android:name="android.intent.action.VIEW"></action>
            <category android:name="android.intent.category.DEFAULT"></category>
            <category android:name="android.intent.category.BROWSABLE"></category>
            <data android:scheme="gpsagenda" android:host="twitt" />
        </intent-filter>
    </activity>
</code>```

This should be enough to get you going, I hope.

If something is wrong in here, pleas do comment.

Regards,

iarwain

ContentLicense: CC BY-SA 2.5

Body:
I am trying to write a twitter application on Android target 2.2 (using some sample code that I found on the net and using Marko Gargenta's O'Reilly text). I am stuck with the problem as in the log below. The source code is given first followed by the log. Any idea what's going wrong here ? Also does anyone have or can point to a sample jtwitter code working on Android.

Thanks,
Ravi

protected String doInBackground(String... statuses) {
  try {

         //Autho information
         /*OAuthSignpostClient oauthclient = new OAuthSignpostClient(cons_key,
           cons_secret, access_token, access_secret);*/

         OAuthSignpostClient oauthclient = new OAuthSignpostClient(access_token, access_secret,"oob");

         //***POSTING TO TWITTER CURRENTLY DOES NOT WORK WITH THIS INTERFACE
         twitter = new Twitter(mytwitterusername, oauthclient);
         //twitter.setAPIRootUrl("http://learningandroid.status.net/api");

   //***POSTING TO TWITTER CURRENTLY DOES NOT WORK WITH THIS INTERFACE
   Log.i(Logtag, "Status currently is " + statuses[0]);

   Twitter.Status status = twitter.updateStatus(statuses[0]);
   //return status.text;
   return statuses[0];
  } catch (TwitterException e) {
   Log.e(Logtag, e.toString());
   e.printStackTrace();
   return "Failed to post to Twitter";
  }

}

Log file:

E/dalvikvm(  719): Could not find method javax.swing.JOptionPane.showInputDialog, referenced from method winterwell.jtwi
tter.OAuthSignpostClient.askUser
W/dalvikvm(  719): VFY: unable to resolve static method 443: Ljavax/swing/JOptionPane;.showInputDialog (Ljava/lang/Objec
t;)Ljava/lang/String;
W/dalvikvm(  719): VFY:  rejecting opcode 0x71 at 0x0000
W/dalvikvm(  719): VFY:  rejected Lwinterwell/jtwitter/OAuthSignpostClient;.askUser (Ljava/lang/String;)Ljava/lang/Strin
g;
W/dalvikvm(  719): Verifier rejected class Lwinterwell/jtwitter/OAuthSignpostClient;
W/dalvikvm(  719): threadid=17: thread exiting with uncaught exception (group=0x4000fe70)
E/AndroidRuntime(  719): Uncaught handler: thread AsyncTask #1 exiting due to uncaught exception
E/AndroidRuntime(  719): java.lang.RuntimeException: An error occured while executing doInBackground()
E/AndroidRuntime(  719):        at android.os.AsyncTask$3.done(AsyncTask.java:200)
E/AndroidRuntime(  719):        at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:234)
E/AndroidRuntime(  719):        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:258)
E/AndroidRuntime(  719):        at java.util.concurrent.FutureTask.run(FutureTask.java:122)
E/AndroidRuntime(  719):        at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:648)
E/AndroidRuntime(  719):        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:673)
E/AndroidRuntime(  719):        at java.lang.Thread.run(Thread.java:1058)
E/AndroidRuntime(  719): Caused by: java.lang.VerifyError: winterwell.jtwitter.OAuthSignpostClient
E/AndroidRuntime(  719):        at com.ravi.tweeto.StatusActivity$PostToTwitter.doInBackground(StatusActivity.java:81)
E/AndroidRuntime(  719):        at com.ravi.tweeto.StatusActivity$PostToTwitter.doInBackground(StatusActivity.java:1)
E/AndroidRuntime(  719):        at android.os.AsyncTask$2.call(AsyncTask.java:185)
E/AndroidRuntime(  719):        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:256)
E/AndroidRuntime(  719):        ... 4 more
I/Process (  585): Sending signal. PID: 719 SIG: 3
I/dalvikvm(  719): threadid=7: reacting to signal 3
I/dalvikvm(  719): Wrote stack trace to '/data/anr/traces.txt'
----

Body:
I found most of the code I use somewhere on GitHub (can't find the exact link right now)
A few searches on snippets of the code send me here, but I don't think that was the exact site I got it from.

But this is what I have in my semi-working code.

OAUTH.java

import junit.framework.Assert;
import oauth.signpost.OAuth;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.exception.OAuthNotAuthorizedException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;

public class OAUTH extends Activity {
private static final String TAG = "OAUTH";

public static final String USER_TOKEN = "user_token";
public static final String USER_SECRET = "user_secret";
public static final String REQUEST_TOKEN = "request_token";
public static final String REQUEST_SECRET = "request_secret";

public static final String TWITTER_REQUEST_TOKEN_URL = "http://twitter.com/oauth/request_token";
public static final String TWITTER_ACCESS_TOKEN_URL = "http://twitter.com/oauth/access_token";
public static final String TWITTER_AUTHORIZE_URL = "http://twitter.com/oauth/authorize";

private static final Uri CALLBACK_URI = Uri.parse("gpsagenda://twitt");

public static final String PREFS = "MyPrefsFile";

private OAuthConsumer mConsumer = null;
private OAuthProvider mProvider = null;

SharedPreferences mSettings;

public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    // We don't need to worry about any saved states: we can reconstruct the state
    mConsumer = new CommonsHttpOAuthConsumer(
            "myKey",
            "mySecret");

    mProvider = new CommonsHttpOAuthProvider (
            TWITTER_REQUEST_TOKEN_URL,
            TWITTER_ACCESS_TOKEN_URL,
            TWITTER_AUTHORIZE_URL);

    // It turns out this was the missing thing to making standard Activity launch mode work
    mProvider.setOAuth10a(true);

    mSettings = this.getSharedPreferences(PREFS, Context.MODE_PRIVATE);

    Intent i = this.getIntent();
    if (i.getData() == null) {
        try {
                            // This is really important. If you were able to register your real callback Uri with Twitter, and not some fake Uri
                            // like I registered when I wrote this example, you need to send null as the callback Uri in this function call. Then
                            // Twitter will correctly process your callback redirection
            String authUrl = mProvider.retrieveRequestToken(mConsumer, CALLBACK_URI.toString());
            saveRequestInformation(mSettings, mConsumer.getToken(), mConsumer.getTokenSecret());
            this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
        } catch (OAuthMessageSignerException e) {
            e.printStackTrace();
        } catch (OAuthNotAuthorizedException e) {
            e.printStackTrace();
        } catch (OAuthExpectationFailedException e) {
            e.printStackTrace();
        } catch (OAuthCommunicationException e) {
            e.printStackTrace();
        }
    }
}

@Override
protected void onResume() {
    super.onResume();

    Uri uri = getIntent().getData();
    if (uri != null && CALLBACK_URI.getScheme().equals(uri.getScheme())) {
        String token = mSettings.getString(OAUTH.REQUEST_TOKEN, null);
        String secret = mSettings.getString(OAUTH.REQUEST_SECRET, null);
        Intent i = new Intent(this, DetailsContainer.class); // Currently, how we get back to main activity.

        try {
            if(!(token == null || secret == null)) {
                mConsumer.setTokenWithSecret(token, secret);
            }
            String otoken = uri.getQueryParameter(OAuth.OAUTH_TOKEN);
            String verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);

            // We send out and save the request token, but the secret is not the same as the verifier
            // Apparently, the verifier is decoded to get the secret, which is then compared - crafty
            // This is a sanity check which should never fail - hence the assertion
            Assert.assertEquals(otoken, mConsumer.getToken());

            // This is the moment of truth - we could throw here
            mProvider.retrieveAccessToken(mConsumer, verifier);
            // Now we can retrieve the goodies
            token = mConsumer.getToken();
            secret = mConsumer.getTokenSecret();
            OAUTH.saveAuthInformation(mSettings, token, secret);
            // Clear the request stuff, now that we have the real thing
            OAUTH.saveRequestInformation(mSettings, null, null);
            i.putExtra(USER_TOKEN, token);
            i.putExtra(USER_SECRET, secret);
        } catch (OAuthMessageSignerException e) {
            e.printStackTrace();
        } catch (OAuthNotAuthorizedException e) {
            e.printStackTrace();
        } catch (OAuthExpectationFailedException e) {
            e.printStackTrace();
        } catch (OAuthCommunicationException e) {
            e.printStackTrace();
        } finally {
            startActivity(i); // we either authenticated and have the extras or not, but we're going back
            finish();
        }
    }
}

public static void saveRequestInformation(SharedPreferences settings, String token, String secret) {
    // null means to clear the old values
    SharedPreferences.Editor editor = settings.edit();
    if(token == null) {
        editor.remove(OAUTH.REQUEST_TOKEN);
        Log.d(TAG, "Clearing Request Token");
    }
    else {
        editor.putString(OAUTH.REQUEST_TOKEN, token);
        Log.d(TAG, "Saving Request Token: " + token);
    }
    if (secret == null) {
        editor.remove(OAUTH.REQUEST_SECRET);
        Log.d(TAG, "Clearing Request Secret");
    }
    else {
        editor.putString(OAUTH.REQUEST_SECRET, secret);
        Log.d(TAG, "Saving Request Secret: " + secret);
    }
    editor.commit();

}

public static void saveAuthInformation(SharedPreferences settings, String token, String secret) {
    // null means to clear the old values
    SharedPreferences.Editor editor = settings.edit();
    if(token == null) {
        editor.remove(OAUTH.USER_TOKEN);
        Log.d(TAG, "Clearing OAuth Token");
    }
    else {
        editor.putString(OAUTH.USER_TOKEN, token);
        Log.d(TAG, "Saving OAuth Token: " + token);
    }
    if (secret == null) {
        editor.remove(OAUTH.USER_SECRET);
        Log.d(TAG, "Clearing OAuth Secret");
    }
    else {
        editor.putString(OAUTH.USER_SECRET, secret);
        Log.d(TAG, "Saving OAuth Secret: " + secret);
    }
    editor.commit();

}

}

DetailsTwitter.java (my "implementation")

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.LinkedList;

import oauth.signpost.OAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;

import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.gpsagenda.OAUTH;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class DetailsTwitter extends Activity {

    public SharedPreferences mSettings;

    private LinkedList<UserStatus> mHomeStatus = new LinkedList<UserStatus>();
    public String mToken;
    public String mSecret;
    private OAuthConsumer mConsumer = null;
    private HttpClient mClient;
    private EditText mEditor;
    private TextView mLast;
    private CheckBox mCB;
    private Button mButton;
    private TextView mUser;
    private int ID;

    public static final String VERIFY_URL_STRING = "http://twitter.com/account/verify_credentials.json";
    public static final String PUBLIC_TIMELINE_URL_STRING = "http://twitter.com/statuses/public_timeline.json";
    public static final String USER_TIMELINE_URL_STRING = "http://twitter.com/statuses/user_timeline.json";
    public static final String HOME_TIMELINE_URL_STRING = "http://api.twitter.com/1/statuses/home_timeline.json";
    public static final String FRIENDS_TIMELINE_URL_STRING = "http://api.twitter.com/1/statuses/friends_timeline.json";
    public static final String STATUSES_URL_STRING = "http://twitter.com/statuses/update.json";

    ProgressDialog postDialog = null;

    public static final String TWITTER_REQUEST_TOKEN_URL = "http://twitter.com/oauth/request_token";
    public static final String TWITTER_ACCESS_TOKEN_URL = "http://twitter.com/oauth/access_token";
    public static final String TWITTER_AUTHORIZE_URL = "http://twitter.com/oauth/authorize";

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.detailstwittertab);

        HttpParams parameters = new BasicHttpParams();
        HttpProtocolParams.setVersion(parameters, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(parameters, HTTP.DEFAULT_CONTENT_CHARSET);
        HttpProtocolParams.setUseExpectContinue(parameters, false);
        HttpConnectionParams.setTcpNoDelay(parameters, true);
        HttpConnectionParams.setSocketBufferSize(parameters, 8192);

        SchemeRegistry schReg = new SchemeRegistry();
        schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        ClientConnectionManager tsccm = new ThreadSafeClientConnManager(parameters, schReg);
        mClient = new DefaultHttpClient(tsccm, parameters);

        mCB = (CheckBox) this.findViewById(R.id.enable);
        mCB.setChecked(false);
        mEditor = (EditText) this.findViewById(R.id.editor);
        mButton = (Button) this.findViewById(R.id.post);
        mUser = (TextView) this.findViewById(R.id.user);
        mLast = (TextView) this.findViewById(R.id.last);

        mSettings = getSharedPreferences(OAUTH.PREFS, Context.MODE_PRIVATE);
        mConsumer = new CommonsHttpOAuthConsumer(
            "myKey",
            "mySecret");
    }

    public void PostTweet(View v) {
        String postString = mEditor.getText().toString();
        if (postString.length() == 0) {
            Toast.makeText(this, getText(R.string.tweet_empty), Toast.LENGTH_SHORT).show();
        } else {
            BitlyAndroid bitly = new BitlyAndroid("iarwain01", "R_1bffd0176aa731a27e5b2d23cf043199");
            String shortUrl = "";
            // Try to get the corresponding ID of the POI
           try
           {
               ID = getIntent().getExtras().getInt("id");
           } catch (NullPointerException e)
           {
               e.printStackTrace();
           }
            try {
                shortUrl = bitly.getShortUrl("http://gpsagenda.ikdoeict.be/projecten2/index.php?module=places&id=" + ID);
            } catch (Exception e) {
                Log.e("Debug", "Link shortening failed!");
                e.printStackTrace();
            }

            new PostTask().execute(postString + " " + shortUrl);
        }
    }

    protected void onFinish() {
        mClient.getConnectionManager().shutdown();
    }

    public void ConnectWithTwitter(View v)
    {
        if(mCB.isChecked()) {
            Intent i = new Intent(this, OAUTH.class);
            startActivity(i);
        } else {
            OAUTH.saveAuthInformation(mSettings, null, null);
            mButton.setEnabled(false);
            mEditor.setEnabled(false);
            mCB.setChecked(false);
            mUser.setText("");
        }
        mCB.setChecked(false); // the oauth callback will set it to the proper state
    }

    @Override
    public void onResume()
    {
        super.onResume();

        // We look for saved user keys
        if(mSettings.contains(OAUTH.USER_TOKEN) && mSettings.contains(OAUTH.USER_SECRET)) {
            mToken = mSettings.getString(OAUTH.USER_TOKEN, null);
            mSecret = mSettings.getString(OAUTH.USER_SECRET, null);
            if(!(mToken == null || mSecret == null)) {
                mConsumer.setTokenWithSecret(mToken, mSecret);
            }
        }
        new GetCredentialsTask().execute();
    }

    // These parameters are needed to talk to the messaging service
    public HttpParams getParams() {
        // Tweak further as needed for your app
        HttpParams params = new BasicHttpParams();
        // set this to false, or else you'll get an Expectation Failed: error
        HttpProtocolParams.setUseExpectContinue(params, false);

        return params;
    }

    //----------------------------
    // This task posts a message to your message queue on the service.
    private class PostTask extends AsyncTask<String, Void, JSONObject> {

        ProgressDialog postDialog;

        @Override
        protected void onPreExecute() {
            postDialog = ProgressDialog.show(DetailsTwitter.this,
                    getText(R.string.tweet_progress_title),
                    getText(R.string.tweet_progress_text),
                    true,   // indeterminate duration
                    false); // not cancel-able
        }

        @Override
        protected JSONObject doInBackground(String... params) {

            JSONObject jso = null;
            try {
                HttpPost post = new HttpPost("http://twitter.com/statuses/update.json");
                LinkedList<BasicNameValuePair> out = new LinkedList<BasicNameValuePair>();
                out.add(new BasicNameValuePair("status", params[0]));
                post.setEntity(new UrlEncodedFormEntity(out, HTTP.UTF_8));
                post.setParams(getParams());
                // sign the request to authenticate
                mConsumer.sign(post);
                String response = mClient.execute(post, new BasicResponseHandler());
                jso = new JSONObject(response);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (OAuthMessageSignerException e) {
                e.printStackTrace();
            } catch (OAuthExpectationFailedException e) {
                e.printStackTrace();
            } catch (OAuthCommunicationException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            } finally {

            }
            return jso;
        }

        // This is in the UI thread, so we can mess with the UI
        protected void onPostExecute(JSONObject jso) {
            postDialog.dismiss();
            if(jso != null) { // authorization succeeded, the json object contains the user information
                mEditor.setText("");
                mLast.setText(getCurrentTweet(jso));
            } else {
                mLast.setText(getText(R.string.tweet_error));
            }
        }
    }

    // Get stuff from the two types of Twitter JSONObject we deal with: credentials and status
    private String getCurrentTweet(JSONObject status) {
        return status.optString("text", getString(R.string.bad_value));
    }

    //----------------------------
    // This task is run on every onResume(), to make sure the current credentials are valid.
    // This is probably overkill for a non-educational program
    private class GetCredentialsTask extends AsyncTask<Void, Void, JSONObject> {

        ProgressDialog authDialog;

        @Override
        protected void onPreExecute() {
            authDialog = ProgressDialog.show(DetailsTwitter.this,
                getText(R.string.auth_progress_title),
                getText(R.string.auth_progress_text),
                true,   // indeterminate duration
                false); // not cancel-able
        }

        @Override
        protected JSONObject doInBackground(Void... arg0) {
            JSONObject jso = null;
            HttpGet get = new HttpGet(VERIFY_URL_STRING);
            try {
                mConsumer.sign(get);
                String response = mClient.execute(get, new BasicResponseHandler());
                jso = new JSONObject(response);
            } catch (OAuthMessageSignerException e) {
                e.printStackTrace();
            } catch (OAuthExpectationFailedException e) {
                e.printStackTrace();
            } catch (OAuthCommunicationException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return jso;
        }

        // This is in the UI thread, so we can mess with the UI
        protected void onPostExecute(JSONObject jso) {
            authDialog.dismiss();
            mCB.setChecked(jso != null);
            mButton.setEnabled(jso != null);
            mEditor.setEnabled(jso != null);
            mUser.setText(jso != null ? getUserName(jso) : getString(R.string.userhint));
            mLast.setText(jso != null ? getLastTweet(jso) : getString(R.string.userhint));
            if(jso != null) {
                TimelineSelector ss = new TimelineSelector(HOME_TIMELINE_URL_STRING);
                new GetTimelineTask().execute(ss);
            }
        }
    }

    private String getLastTweet(JSONObject credentials) {
        try {
            JSONObject status = credentials.getJSONObject("status");
            return getCurrentTweet(status);
        } catch (JSONException e) {
            e.printStackTrace();
            return getString(R.string.tweet_error);
        }
    }

    private String getUserName(JSONObject credentials) {
        return credentials.optString("name", getString(R.string.bad_value));
    }

    private class TimelineSelector extends Object {
        public String url; // the url to perform the query from
        // not all these apply to every url - you are responsible
        public Long since_id; // ids newer than this will be fetched
        public Long max_id; // ids older than this will be fetched
        public Integer count; // # of tweets to fetch Max is 200
        public Integer page; // # of page to fetch (with limits)

        public TimelineSelector(String u) {
            url = u;
            max_id = null;
            since_id = null;
            count = null;
            page = null;
        }

        @SuppressWarnings("unused")
        public TimelineSelector(String u, Long since, Long max, Integer cnt, Integer pg) {
            url = u;
            max_id = max;
            since_id = since;
            count = cnt;
            page = pg;
        }
    }

    private class UserStatus {

        JSONObject mStatus;
        @SuppressWarnings("unused")
        JSONObject mUser;

        public UserStatus(JSONObject status) throws JSONException {

            mStatus = status;
            mUser = status.getJSONObject("user");
        }
        @SuppressWarnings("unused")
        public long getId() {
            return mStatus.optLong("id", -1);
        }
        /*public String getUserName() {
            return mUser.optString("name", getString(R.string.bad_value));
        }
        public String getText() {
            return getCurrentTweet(mStatus);
        }
        public String getCreatedAt() {
            @SuppressWarnings("unused")
            Time ret1 = new Time();
            return mStatus.optString("created_at", getString(R.string.bad_value));
        }*/
    }

    private class GetTimelineTask extends AsyncTask<TimelineSelector, Void, JSONArray> {

        @Override
        protected JSONArray doInBackground(TimelineSelector... params) {
            JSONArray array = null;
            try {
                for(int i = 0; i < params.length; ++i) {
                    Uri sUri = Uri.parse(params[i].url);
                    Uri.Builder builder = sUri.buildUpon();
                    if(params[i].since_id != null) {
                        builder.appendQueryParameter("since_id", String.valueOf(params[i].since_id));
                    } else if (params[i].max_id != null) { // these are mutually exclusive
                        builder.appendQueryParameter("max_id", String.valueOf(params[i].max_id));
                    }
                    if(params[i].count != null) {
                        builder.appendQueryParameter("count", String.valueOf((params[i].count > 200) ? 200 : params[i].count));
                    }
                    if(params[i].page != null) {
                        builder.appendQueryParameter("page", String.valueOf(params[i].page));
                    }
                    HttpGet get = new HttpGet(builder.build().toString());
                    mConsumer.sign(get);
                    String response = mClient.execute(get, new BasicResponseHandler());
                    array = new JSONArray(response);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (OAuthMessageSignerException e) {
                e.printStackTrace();
            } catch (OAuthExpectationFailedException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (OAuthCommunicationException e) {
                e.printStackTrace();
            }
            return array;
        }

        // This is in the UI thread, so we can mess with the UI
        protected void onPostExecute(JSONArray array) {
            if(array != null) {
                try {
                    for(int i = 0; i < array.length(); ++i) {
                        JSONObject status = array.getJSONObject(i);
                        UserStatus s = new UserStatus(status);
                        mHomeStatus.add(s);
                    }
                    //mAA.notifyDataSetChanged();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
            }
        }
    }
}

My AndroidManifest.xml

    <activity android:name="DetailsTwitter" />
    <activity android:name="OAUTH" >
        <intent-filter>
            <action android:name="android.intent.action.VIEW"></action>
            <category android:name="android.intent.category.DEFAULT"></category>
            <category android:name="android.intent.category.BROWSABLE"></category>
            <data android:scheme="gpsagenda" android:host="twitt" />
        </intent-filter>
    </activity>

This should be enough to get you going, I hope.

If something is wrong in here, pleas do comment.

Regards,

iarwain


来源: stackexchange

问:
how to remove a field from tuple in apache pig
i have a code as follow:

B_t= LOAD 'test.csv' USING PigStorage('\t') as (id:chararray,usr_id:chararray,weed:chararray,ip:chararray);

in above, i have field with name weed, i would like remove this field from record with filter command without use codes as follow:

B_f = FOREACH B_t GENERATE id , usr_id, ip

or

B_t= LOAD 'test.csv' USING PigStorage('\t')  $0 as id, ....;

have anyone idea???

答: Why in the world u want to use Filter only. Filter is used emit the fields based on condition, not remove the entire field. Foreach -- Generate is the best way.</p>

ContentLicense: CC BY-SA 3.0


问:
Dataweave empty array input add default key:value
is there a way to map a http response which is in json array to another json map also considering default values i.e when it is empty map a default key pair?

input

```<code>{

"key1": []
"key2":[x,y]
}
</code>```

req output

```<code>{"table":[{
  "a-key1": "deafault-value",
  "a-key2": "x",
  "b-key2": "y"
  }]
}
</code>```

答:
You can use default keyword only in case of null but for blank and empty array you can use something like

```<code>%dw 1.0
%output application/json
%function getDefault(inputdata, defaultvalue)  inputdata when inputdata != null and (sizeOf inputdata) > 0 otherwise defaultvalue
---
{"table": [{
  "a-key1": getDefault(payload.key1,"defaultKey1") ,
  "a-key2": getDefault(payload.key2,"defaultKey2"),
  "b-key2": getDefault(payload.key3,"defaultKey2")

  }]
}
</code>```

assume payload is header or query params.

Hope this helps.

Body:
is there a way to map a http response which is in json array to another json map also considering default values i.e when it is empty map a default key pair?

input

{

"key1": []
"key2":[x,y]
}

req output

{"table":[{
  "a-key1": "deafault-value",
  "a-key2": "x",
  "b-key2": "y"
  }]
}

Body:
You can use default keyword only in case of null but for blank and empty array you can use something like

%dw 1.0
%output application/json
%function getDefault(inputdata, defaultvalue)  inputdata when inputdata != null and (sizeOf inputdata) > 0 otherwise defaultvalue
---
{"table": [{
  "a-key1": getDefault(payload.key1,"defaultKey1") ,
  "a-key2": getDefault(payload.key2,"defaultKey2"),
  "b-key2": getDefault(payload.key3,"defaultKey2")

  }]
}

assume payload is header or query params.

Hope this helps.


问:
Stop JavaScript function after 3 seconds
Heyo,

I want to call a function that disables the scrollwheel while the Preloader is shown. But after the Preloader is gone, the scrollwhell should be usable again.
I got the function which disables the scrollwheel allready. Now I need a simple code which makes it run only the first 3 seconds.

My anitscrollwheel function looks like so: window.onwheel = function(){ return false; }

答:
You can do something like that</p>

```<code>var enable_scroll = false;

//When preloader ends, set enable_scroll = true;

window.onwheel = function(){
    if(enable_scroll == false) {
        return false;
    }
}
</code>```

Body:
You can do something like that

var enable_scroll = false;

//When preloader ends, set enable_scroll = true;

window.onwheel = function(){
    if(enable_scroll == false) {
        return false;
    }
}


答:
Try this:</p>

```<code><script type="text/javascript">
    var wheelEnabled = false;

    window.onwheel = function() { return wheelEnabled; }

    setTimeout(function() {
        wheelEnabled = true;
    }, 3000);
</script>
</code>```

Title: Stop JavaScript function after 3 seconds

Body:
Heyo,

I want to call a function that disables the scrollwheel while the Preloader is shown. But after the Preloader is gone, the scrollwhell should be usable again.
I got the function which disables the scrollwheel allready. Now I need a simple code which makes it run only the first 3 seconds.

My anitscrollwheel function looks like so: window.onwheel = function(){ return false; }

Body:
Try this:

<script type="text/javascript">
    var wheelEnabled = false;

    window.onwheel = function() { return wheelEnabled; }

    setTimeout(function() {
        wheelEnabled = true;
    }, 3000);
</script>


问:
Dragging a TButton from form to form
I have a Delphi GUI app (with RAD studio 2010) and I want the user to be able to rearrange his workspace. I know how to make TButtons draggable around in the same form, but not how to make the user able to drag a button from one form to another form. When you click and attempt to drag a TButton, I don't think it treats it like a drag-and-drop operation. How do you get a TButton to be drag-and-drop capable across multiple forms?</p>

答:
i don't know how to do it with Delphi's version of DragDrop, but it's perfect for the shell drag-drop with

```<code>IDataObject
</code>```

and

```<code>IDropTarget
</code>```

Except now you're forced to use Window's own API for drag-drop rather than Delphi's limited emulation.

Title: Dragging a TButton from form to form

Body:
i don't know how to do it with Delphi's version of DragDrop, but it's perfect for the shell drag-drop with

IDataObject

and

IDropTarget

Except now you're forced to use Window's own API for drag-drop rather than Delphi's limited emulation.


问:
Error message says 'class' is deprecated, source does not contain 'class'
I've just installed Idris v.1.0 and run the sample code from the Proof section of Rosetta Code, piece by piece. Everything works fine up to the following fragment, which produces the The 'class' keyword is deprecated. Use 'interface' instead. error.

```<code>-- 3.1, Prove that the addition of any two even numbers is even.

evensPlus1 : {a : MyNat} -> {b : MyNat} -> (EvNat a) -> (EvNat b) -> (EvNat (a :+ b))
evensPlus1 ea eb = ?proof31
</code>```

There's not a single piece of 'class' in the source. What could be behind this issue?

答:
Those are just warnings. The %elim-annotations are described in this deprecated chapter of the manual. You can safely delete them and finish the proof, e.g. like this:

```<code>evensPlus1 : (EvNat a) -> (EvNat b) -> (EvNat (a :+ b))
evensPlus1 EvO eb = eb
evensPlus1 (EvSS y) eb = EvSS (evensPlus1 y eb)

congS : {a : MyNat} ->  {b : MyNat} -> (a = b) -> (S a = S b)
congS Refl = Refl
</code>```

Body:
I've just installed Idris v.1.0 and run the sample code from the Proof section of Rosetta Code, piece by piece. Everything works fine up to the following fragment, which produces the The 'class' keyword is deprecated. Use 'interface' instead. error.

-- 3.1, Prove that the addition of any two even numbers is even.

evensPlus1 : {a : MyNat} -> {b : MyNat} -> (EvNat a) -> (EvNat b) -> (EvNat (a :+ b))
evensPlus1 ea eb = ?proof31

There's not a single piece of 'class' in the source. What could be behind this issue?

Body:
Those are just warnings. The %elim-annotations are described in this deprecated chapter of the manual. You can safely delete them and finish the proof, e.g. like this:

evensPlus1 : (EvNat a) -> (EvNat b) -> (EvNat (a :+ b))
evensPlus1 EvO eb = eb
evensPlus1 (EvSS y) eb = EvSS (evensPlus1 y eb)

congS : {a : MyNat} ->  {b : MyNat} -> (a = b) -> (S a = S b)
congS Refl = Refl


问:
Roulette wheel selection with positive and negative fitness values for minimization
I'm doing a genetic algorithm where each inidividual generates 3 new offsprings. The new individuals are evaluated using the fitness function, which may return negative and positive values. What is the correct approach to choose between the offsprings using the roulette wheel selection if I want to minimize?

Some possible values of the fitness function are: fitness_offspring_1 = -98.74; fitness_offspring_2 = -10.1; fitness_offspring_3 = 100.31

I'm working on Python but I only need the idea so I can implement it by myself.

答:
This is how I implemented it in JavaScript, to give you a general idea:

```<code>    var totalFitness = 0;
    var minimalFitness = 0;

    for(var genome in this.population){
      var score = this.population[genome].score;
      minimalFitness = score < minimalFitness ? score : minimalFitness;
      totalFitness += score
    }

    minimalFitness = Math.abs(minimalFitness);
    totalFitness += minimalFitness * this.popsize;

    var random = Math.random() * totalFitness
    var value = 0;

    for(var genome in this.population){
      genome = this.population[genome];
      value += genome.score + minimalFitness;
      if(random < value) return genome;
    }

    // if all scores equal, return random genome
    return this.population[Math.floor(Math.random() * this.population.length)];
</code>```

However, just as @umutto has mentioned, this gives the genome with the lowest score no chance of being selected. So you could artificially add a little bit of fitness to each genome, so that even the lowest invidivudla has a chance. Note: I didn't implement that small bias in the above code @umutto mentioned.

Body:
This is how I implemented it in JavaScript, to give you a general idea:

    var totalFitness = 0;
    var minimalFitness = 0;

    for(var genome in this.population){
      var score = this.population[genome].score;
      minimalFitness = score < minimalFitness ? score : minimalFitness;
      totalFitness += score
    }

    minimalFitness = Math.abs(minimalFitness);
    totalFitness += minimalFitness * this.popsize;

    var random = Math.random() * totalFitness
    var value = 0;

    for(var genome in this.population){
      genome = this.population[genome];
      value += genome.score + minimalFitness;
      if(random < value) return genome;
    }

    // if all scores equal, return random genome
    return this.population[Math.floor(Math.random() * this.population.length)];

However, just as @umutto has mentioned, this gives the genome with the lowest score no chance of being selected. So you could artificially add a little bit of fitness to each genome, so that even the lowest invidivudla has a chance. Note: I didn't implement that small bias in the above code @umutto mentioned.


问:
Laravel jquery ajax successfully returns data, how to display in view?
I have a view which uses jquery ajax.  I have successfully returned data back to the view, how do I display the new data in my view?  Here is my code:

```<code>$( function() {
        $( "#slider-range-ratio" ).slider({
            range: false,
            min: 0,
            max: 100,
            step: 1,
            value: 50,

            stop: function( event, ui ) {
                var formdata = $("#search_form").serialize();

                $.ajax({
                    type: "POST",
                    url: "{{ url('search') }}",
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    data: formdata,
                    cache: false,
                    success: function(sites){
                        //console.log(sites);
                        $('#search_panel').html(sites);
                    }
                });
            }
        });
    } );
</code>```

And my view:

```<code>{{ Form::open(['id' => 'search_form']) }}
<div class="panel-body grey-background" id="search_panel">
                    <input type="hidden" id="token" value="{{ csrf_token() }}">
                        <div class="col-xs-12 col-sm-12 col-md-8 col-lg-8">
                            <!-- Start Search Results -->
                            @foreach($sites as $site)
                                @if($site->is_front_page == true)
                                    <div class="panel panel-default">
                                        <div class="panel-body">

                                            <div class="row">
                                                <div class="col-xs-12 col-sm-12 col-md-4 col-lg-4">

                                                    <div class="row">
                                                        <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                                                            <span class="small pull-left">
                                                                Rank: {{ $site->rank }}
                                                            </span>
                                                        </div>
                                                        <div class="col-xs-8 col-sm-8 col-md-8 col-lg-8">
                                                            <a href="{{ url('link/' . $site->url_name) }}">
                                                                <strong class="site-title text-primary pull-right">
                                                                    {{ $site->display_name }}
                                                                </strong>
                                                            </a>
                                                        </div>
                                                    </div>
                                                 </div>
                                              </div>
                                           </div>
                                        </div>
                                        @endif
                                        @endforeach
                                     </div>
                                  </div>
</code>```

The $sites variable in my view holds an array of objects.  When I check my console the correct sites data is returned back, I want to display the sites data in my foreach loop in the view.

答:
first you should put and id for every element that is produced with php :

for exmple:

```<code><span class="small pull-left">
    Rank <span id="rank_{{$site->id}}"> {{ $site->rank }} </span>
</span>
</code>```

Then loop trough elements with id = rank_1, rank_2 , ... and fill them with you javaScript value:

```<code>$("span:regex(class, .*rank_.*)").each(function(item){
     item.html('your value')
})
</code>```

Body:
I have a view which uses jquery ajax.  I have successfully returned data back to the view, how do I display the new data in my view?  Here is my code:

$( function() {
        $( "#slider-range-ratio" ).slider({
            range: false,
            min: 0,
            max: 100,
            step: 1,
            value: 50,

            stop: function( event, ui ) {
                var formdata = $("#search_form").serialize();

                $.ajax({
                    type: "POST",
                    url: "{{ url('search') }}",
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    data: formdata,
                    cache: false,
                    success: function(sites){
                        //console.log(sites);
                        $('#search_panel').html(sites);
                    }
                });
            }
        });
    } );

And my view:

{{ Form::open(['id' => 'search_form']) }}

                    <input type="hidden" id="token" value="{{ csrf_token() }}">

                            @foreach($sites as $site)
                                @if($site->is_front_page == true)

                                                                Rank: {{ $site->rank }}

                                                            url_name) }}">

                                                                    {{ $site->display_name }}

                                        @endif
                                        @endforeach

The $sites variable in my view holds an array of objects.  When I check my console the correct sites data is returned back, I want to display the sites data in my foreach loop in the view.

Body:
first you should put and id for every element that is produced with php :

for exmple:

<span class="small pull-left">
    Rank <span id="rank_{{$site->id}}"> {{ $site->rank }} </span>
</span>

Then loop trough elements with id = rank_1, rank_2 , ... and fill them with you javaScript value:

$("span:regex(class, .*rank_.*)").each(function(item){
     item.html('your value')
})


问:
How do you test whether Silverlight can play a stream?
I want to write a method like the one bellow.  However, in the event that Silverlight is unable to play the stream natively, I would like it to go through a list of MediaStreamSource classes, and try each one in turn till either one of them works, or it has no more to try.  My question is, how do I tell whether the method below is sufficient for a particular stream.

```<code>public static  void OpenMedia(this MediaElement ME, Stream FileData)
{
  ME.SetSource(FileData);
}
</code>```

I need some code to execute in the event that this fails to play the media.

答:
I'm not sure if you are looking for testing failure or testing for the ability to play the media type so...

You can add an event handler for MediaFailed, either in the XAML or he code behind for both cases.  Checking for playability proactively would take some creativity, such as having some "sample" media files of various types that are very small (< 1 second) and silent which serve the purpose of testing playability and it would be transparent to the user.

For C# code behind wire the event, and add the new event:

```<code>void yourPage_Loaded(object sender, RoutedEventArgs e)
{
  ME.MediaFailed += new EventHandler<ExceptionRoutedEventArgs>(ME_MediaFailed);
}

void ME_MediaFailed(object sender, ExceptionRoutedEventArgs e)
{
  add your code to handle the exception here.
}
</code>```

Body:
I want to write a method like the one bellow.  However, in the event that Silverlight is unable to play the stream natively, I would like it to go through a list of MediaStreamSource classes, and try each one in turn till either one of them works, or it has no more to try.  My question is, how do I tell whether the method below is sufficient for a particular stream.

public static  void OpenMedia(this MediaElement ME, Stream FileData)
{
  ME.SetSource(FileData);
}

I need some code to execute in the event that this fails to play the media.

Body:
I'm not sure if you are looking for testing failure or testing for the ability to play the media type so...

You can add an event handler for MediaFailed, either in the XAML or he code behind for both cases.  Checking for playability proactively would take some creativity, such as having some "sample" media files of various types that are very small (< 1 second) and silent which serve the purpose of testing playability and it would be transparent to the user.

For C# code behind wire the event, and add the new event:

void yourPage_Loaded(object sender, RoutedEventArgs e)
{
  ME.MediaFailed += new EventHandler<ExceptionRoutedEventArgs>(ME_MediaFailed);
}

void ME_MediaFailed(object sender, ExceptionRoutedEventArgs e)
{
  add your code to handle the exception here.
}


问:
ADFS MFA throws Error for some Users/Client PCs
We have a standard ADFS Server for Office 356. I created now a MVC Intranet/Page that i secure also via ADFS. For the ADFS i have written two MFA Providers, one with SMS and one with TOTP. All is up and running.
Login is okay for all Users, but the MFA (StepUp Auth for some Pages) fails for some users or some machines sometimes. (randomly they work or dont)

An error (thrown by ADFS) will look in the clients browser like this:

Activity ID: 00000000-0000-0000-c82a-0080010000d3
    Relying party: Portal
    Error time: Wed, 07 Jun 2017 14:08:56 GMT
    Cookie: enabled
    User agent string: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0

or this:

Activity ID: 00000000-0000-0000-e525-0080000000fb
    Relying party: Portal Developer
    Error time: Fri, 02 Jun 2017 13:53:47 GMT
    Cookie: enabled
    User agent string: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 10.0; WOW64; Trident/8.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729)

I have activated the ADFS Trace/Debug Log. Unfortunatly i cant find any errors in the EventVwr on the ADFS Server.
Any Ideas what i can do?

答:
Problem solved.
I fugured now out, that have more than one ADFS Server. I had the MFA Provider installed on only one Server.
On the Second ADFS Server the Log, with the Errors, and everything is there.
Sorry. And sorry to myself.</p>


问:
How to filter GMSPlacesAutocompleteTypeFilter to obtain the Country result for both United states and canada
```<code>let filter = GMSAutocompleteFilter()
        filter.type = GMSPlacesAutocompleteTypeFilter.city
        filter.country = "USA" || "CA"
</code>```

<p>how to get 2 country results in google autocomplete </p>

答: If you check country property in GMSAutocompleteFilter class then you will found that it is string so I think you can't set multiple country in your filter. If it's allowing multiple country then it should be array or any collection instead of string! and in documentation also they haven't mentioned for multiple countries in filter! So, I think you can't set more than one country at a time in one filter!

Body:
let filter = GMSAutocompleteFilter()
        filter.type = GMSPlacesAutocompleteTypeFilter.city
        filter.country = "USA" || "CA"

how to get 2 country results in google autocomplete


问:
Keyframe animations
I am a bit confused on how keyframes work exactly in this demo. Whats confusing me is that 0% and 100% are not defined but 25% and 75% are. But at 0% the 25% keyframe is active. I thought it wouldn't be active until 25% through the animation until it hits the 75% keyframe. Also when does the 75% keyframe stop 100%? If you could explain exactly what is happening it would be appreciated. I hope this question is clear. Thanks.

@-webkit-keyframes pulse {
  25% {
    -webkit-transform: scale(1.2);
    transform: scale(1.2);
  }
  75% {
    -webkit-transform: scale(0.8);
    transform: scale(0.8);
  }
}

@keyframes pulse {
  25% {
    -webkit-transform: scale(1.2);
    -ms-transform: scale(1.2);
    transform: scale(1.2);
  }
  75% {
    -webkit-transform: scale(0.8);
    -ms-transform: scale(0.8);
    transform: scale(0.8);
  }
}

.pulse {
  display: inline-block;
  -webkit-transform: translateZ(0);
  -ms-transform: translateZ(0);
  transform: translateZ(0);
  box-shadow: 0 0 1px rgba(0, 0, 0, 0);
  width: 50px;
  height: 50px;
  background-color: blue;
}

.pulse:hover {
  -webkit-animation-name: pulse;
  animation-name: pulse;
  -webkit-animation-duration: 5s;
  animation-duration: 5s;
  -webkit-animation-timing-function: linear;
  animation-timing-function: linear;
  -webkit-animation-iteration-count: infinite;
  animation-iteration-count: infinite;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="pulse">

</div></code>```

答:
hi if you don't need animation to happen then add

```<code>@keyframes <animation name>
{

  0%,25%
  {
  animation here
  }

  75%,100%
  {
  animation here
  }

}
</code>```

what happens here is animation don't start up-to 25%, from 25% to 75% animation plays and stops after 75% until it reaches 100%

Title: Keyframe animations

Body:
hi if you don't need animation to happen then add

@keyframes <animation name>
{

  0%,25%
  {
  animation here
  }

  75%,100%
  {
  animation here
  }

}

what happens here is animation don't start up-to 25%, from 25% to 75% animation plays and stops after 75% until it reaches 100%


问:
CRF++/Wapiti include category of entire sentence as feature
How can I represent category of sentence predicted from Naive Bayes as a feature in CRF++ or Wapiti?

For instance, if the sentence, Tumblr merges with Yahoo., is classified as Business, then while composing the training file for crf, where can I indicate the label Business as a feature? And how should then the template be modeled?

Should the train file be like this

```<code>Tumblr    business    ORG
merges    business    O
with     business    O
Yahoo    business    ORG
</code>```

Or only include the category with the ORG label? How so? And the template file?

答:
As far as I know your train file is the only way to include sentence-level annotation, unless you'd consider adapting / implementing a CRF that takes into account sentence-level features.

If you have enough training data and a limited number of categories, this method would probably affect a low weight to sentence categories: it would only be used to distinguish named entities whenever they are ambiguous and when the computed NE categories probabilities are somehow close.

Best way would indeed be to train with/without this feature and see if it improves NER! Should be an interesting experimentation :)

Body:
How can I represent category of sentence predicted from Naive Bayes as a feature in CRF++ or Wapiti?

For instance, if the sentence, Tumblr merges with Yahoo., is classified as Business, then while composing the training file for crf, where can I indicate the label Business as a feature? And how should then the template be modeled?

Should the train file be like this

Tumblr    business    ORG
merges    business    O
with     business    O
Yahoo    business    ORG

Or only include the category with the ORG label? How so? And the template file?


问:
Issue on removing item from clustermanager
In my Android application, I have to delete and re-add a cluster item in my GoogleMap, that represents my current location. But when I run this code:

```<code>clusterMng.remove(myitem);
</code>```

I get this Exception:

```<code>java.lang.UnsupportedOperationException: NonHierarchicalDistanceBasedAlgorithm.remove
not implemented.
</code>```

Can someone explain to me what this means?
Do I have to rewrite some methods of ClusterManager.java in the external library? Or can I simply change my algorithm?

答:
I have found removeItem(T item) in the source code of ClusterManager.java
Tested, it works
Link to source code https://github.com/googlemaps/android-maps-utils/blob/master/library/src/com/google/maps/android/clustering/ClusterManager.java

Body:
In my Android application, I have to delete and re-add a cluster item in my GoogleMap, that represents my current location. But when I run this code:

clusterMng.remove(myitem);

I get this Exception:

java.lang.UnsupportedOperationException: NonHierarchicalDistanceBasedAlgorithm.remove
not implemented.

Can someone explain to me what this means?
Do I have to rewrite some methods of ClusterManager.java in the external library? Or can I simply change my algorithm?


问:
Prgrammably making excel spreadsheets (97 - 2003 format)
I was wondering how difficult it would be to make an application like this. Basically, I have some old html files that use tables. I want to put these tables into excel for easier reading and manipulation. I only have text, I have no numbers of formulas or anything.

Are there any tutorials on how to do this sort of thing?

The application would produce .xls

Thanks

答: Looks like there's another alternative called ExcelFormat. I didn't try it, though.</p>


问:
How to replace a button and re position it dynamically?
I have a text box and a add button next to it, when I click on add button I am able to add a text box and delete button next to it. Now I want the add button on the first row to be changed to delete and the add button should be re-positioned below two rows, when the second row delete button  is clicked (the second row is deleted )the add button should go back to the first row and replace delete button. It should look like following.

How do I achieve this?

答:
I did the same in one of my project. The code is bit complicated to do in Jface/SWT. Adding and removing widgets on composite will be bit heavy task. This will reduce UI performance.

If you use Jface tableviewer instead of creating composite, you will get better UI performance and good look as well.  In table viewer in one column you can show textboxes and in one column you can show buttons. You can write table column Editing support/label providers to show the buttons.

With this approach you will be able show buttons for all rows or when you click on any cell you want to add or delete.

I can't share the code snippet right now, due to some reasons, but if you need I will share it on weekends


问:
Failed to initialize output adapters while starting LiveDemo project's instance in FiWARE CEP
Error occurred while starting while starting LiveDemo project's instance in FiWARE CEP. it fails to initialize the output adapters.</p>

```<code>INFO [Thread-27] com.ibm.hrl.proton.server.adapter.OutputServer.run Proton output server started, listening on output port: 3302
WARNING [pool-11-thread-1] com.ibm.hrl.proton.server.adapter.AbstractServer.startAdapters initializeAdapters: failed to initialize adapter Output adapter for consumer: SimpleFile, reason: No such file or directory
WARNING [pool-11-thread-1] com.ibm.hrl.proton.server.adapter.AbstractServer.startAdapters initializeAdapters: failed to initialize adapter Output adapter for consumer: File, reason: No such file or directory
INFO [Thread-26] com.ibm.hrl.proton.server.adapter.InputServer.run Proton server Started, listening on port: 3002
</code>```

答:
Please correct the path mentioned under "filename" field in the consumer.
Please follow below steps to remove the above mentioned error:
On Fiware PROTON GUI:

```<code>1. click on the Consumers in the resource navigation area.
2. double click on "File" consumer
3. update value of "filename" field in the Editing area(in the center).
   note: make sure the path is absolute not relative as tomcat's directory location can different in various linux falvours.
and make sure the all the directories mentioned in the path exists(file will be created automatically while initializing the adapter).
4. do the same for "SimpleFile" consumer.
5. click on "Save and Export" button at the top.
6. click on "Export to external repository" in the pop-up window.
7. Input destination and click ok.
</code>```

After above steps stop the instance and start it again via REST API calls.

stop the instance:

PUT
  //localhost:8080/ProtonOnWebServerAdmin/resources/instances/ProtonOnWebServer
  {"action":"ChangeState","state":"stop"}

start the instance:

PUT
  //localhost:8080/ProtonOnWebServerAdmin/resources/instances/ProtonOnWebServer
  {"action":"ChangeState","state":"start"}

Body:
Error occurred while starting while starting LiveDemo project's instance in FiWARE CEP. it fails to initialize the output adapters.

INFO [Thread-27] com.ibm.hrl.proton.server.adapter.OutputServer.run Proton output server started, listening on output port: 3302
WARNING [pool-11-thread-1] com.ibm.hrl.proton.server.adapter.AbstractServer.startAdapters initializeAdapters: failed to initialize adapter Output adapter for consumer: SimpleFile, reason: No such file or directory
WARNING [pool-11-thread-1] com.ibm.hrl.proton.server.adapter.AbstractServer.startAdapters initializeAdapters: failed to initialize adapter Output adapter for consumer: File, reason: No such file or directory
INFO [Thread-26] com.ibm.hrl.proton.server.adapter.InputServer.run Proton server Started, listening on port: 3002

Body:
Please correct the path mentioned under "filename" field in the consumer.
Please follow below steps to remove the above mentioned error:
On Fiware PROTON GUI:

1. click on the Consumers in the resource navigation area.
2. double click on "File" consumer
3. update value of "filename" field in the Editing area(in the center).
   note: make sure the path is absolute not relative as tomcat's directory location can different in various linux falvours.
and make sure the all the directories mentioned in the path exists(file will be created automatically while initializing the adapter).
4. do the same for "SimpleFile" consumer.
5. click on "Save and Export" button at the top.
6. click on "Export to external repository" in the pop-up window.
7. Input destination and click ok.

After above steps stop the instance and start it again via REST API calls.

stop the instance:

PUT
  //localhost:8080/ProtonOnWebServerAdmin/resources/instances/ProtonOnWebServer
  {"action":"ChangeState","state":"stop"}

start the instance:

PUT
  //localhost:8080/ProtonOnWebServerAdmin/resources/instances/ProtonOnWebServer
  {"action":"ChangeState","state":"start"}


问:
form.is_valid() is always throwing error and not able to insert values in table in Django
This is my code:
models.py

class SetUpType(models.Model):

```<code>SET_UP_TYPES=(
    ('Dedicated', 'Dedicated'),
    ('Shared','Shared'),
)
SetUpType=models.CharField(max_length=10,choices=SET_UP_TYPES)
</code>```

class SourceTool(models.Model):

```<code>SOURCE_TOOLS=(
    ('ServiceNow','ServiceNow'),
    ('HPSM','HPSM'),
    ('HPSAW','HPSAW'),
    ('Remedy', 'Remedy'),
    ('CA ServiceDesk','CA ServiceDesk'),
    ('EHelpline', 'EHelpline'),
    ('Microsoft SCSM','Microsoft SCSM'),
)
SourceToolName=models.CharField(max_length=30,choices=SOURCE_TOOLS)
</code>```

class Modules(models.Model):

```<code>ModuleName=models.CharField(max_length=30)
</code>```

class DealSize(models.Model):

```<code>DEAL_SIZE=(
    ('<5 mn.','less than 5mn'),
    ('>5 mn.','greater than 5 million'),
)
DealSize=models.CharField(default="<5 mn",max_length=30,choices=DEAL_SIZE)
</code>```

Creating Opportunity Class

class Opportunity(models.Model):

```<code>OppName=models.CharField(max_length=100)
SetUpType=models.ForeignKey(SetUpType,on_delete=models.CASCADE)
SourceTool=models.ForeignKey(SourceTool,on_delete=models.CASCADE)
NumOfUsers=models.IntegerField(blank=True)
NumOfTools=models.IntegerField(blank=True)
Modules=models.ForeignKey(Modules,on_delete=models.CASCADE)
DealSize=models.ForeignKey(DealSize,on_delete=models.CASCADE)
ContractTimeFrame=models.IntegerField(blank=True)
SupportMonths=models.IntegerField(blank=True)
Pricing=models.CharField(max_length=50)
RLS=models.CharField(max_length=50)
</code>```

The SetUpType, SourceTool,Modules and DealSize tables already contain data and the corresponding data of these tables will be displayed in dropdown for respective fields in the below form:

forms.py:

class PreReqForm(forms.ModelForm):

```<code>MODULE_NAMES = (
    ('Incident Management', 'IM'),
    ('Requset for Service', 'SR'),
    ('Problem Management', 'PM'),
    ('Change Management', 'CM'),
)
OppName=forms.CharField(label="Opportunity Name")
setUpTypel1 = SetUpType.objects.all()
setUpTypel2 = [('-----', '-----'),]
for k in setUpTypel1:
    setUpTypel2.append((k.SetUpType, k.SetUpType))
SetUpType=forms.ChoiceField(choices=setUpTypel2,label="Set-up Type")

sourceToolL1 = SourceTool.objects.all()
sourceToolL2 = [('-----', '-----'), ]
for m in sourceToolL1:
    sourceToolL2.append((m.SourceToolName, m.SourceToolName))
SourceTool=forms.ChoiceField(choices=sourceToolL2,label="Source Tool")

NumOfUsers=forms.IntegerField(label="Number of Users")
NumOfTools=forms.IntegerField(label="Number of Tools")
Modules = forms.MultipleChoiceField(choices=MODULE_NAMES, widget=forms.SelectMultiple())
dealSizel1 = DealSize.objects.all()
#dUnique=dealSizel1.distinct('DealSize')
dealSizel2 = [('-----', '-----'), ]
for m in dealSizel1:
    dealSizel2.append((m.DealSize, m.DealSize))
DealSize=forms.ChoiceField(choices=dealSizel2,label="Deal Size")
ContractTimeFrame=forms.IntegerField(label="Contract Time Frame",widget=forms.NumberInput(attrs={'placeholder': 'In Years'}))
#SupportMonths=forms.IntegerField(label="Support Months")

class Meta:
    model = Opportunity
    fields=('OppName','SetUpType','SourceTool','NumOfUsers','NumOfTools','Modules','DealSize','ContractTimeFrame',)
    exclude = ('Pricing','RLS','SupportMonths')
</code>```

Views.py:

def preform(request):

```<code>if request.method == "POST":
    form = PreReqForm(request.POST)
    print request.method
    print request.POST
    print form.errors
    #print request.POST.get['SetUpType']
    if form.is_valid():
        print "valid"
        setuptype=SetUpType(SetUpType=request.POST.get['SetUpType'])
        setuptype.save()
        Opportunity.SetUpType=setuptype

        Opportunity.save()
        return redirect('preDetails')
    else:
        print "invalid"
else:
    form = PreReqForm()

return render(request, "Prerequisites/PreReq1.html", {'form': form})
</code>```

Image of the form

After submitting the form i am getting this on console:
POST

The error is:

ValueError: Cannot assign "u'Shared'": "Opportunity.SetUpType" must be a "SetUpType" instance.
  It is not printing form.errors and form.is_valid() also.

Please help. Thanks in advance.

答: I don't know why but i had a lot of problems using choices with CharField. Finally i switched to IntegerField and it worked like a charm. Give a try :).</p>

Body:
This is my code:
models.py

class SetUpType(models.Model):

SET_UP_TYPES=(
    ('Dedicated', 'Dedicated'),
    ('Shared','Shared'),
)
SetUpType=models.CharField(max_length=10,choices=SET_UP_TYPES)

class SourceTool(models.Model):

SOURCE_TOOLS=(
    ('ServiceNow','ServiceNow'),
    ('HPSM','HPSM'),
    ('HPSAW','HPSAW'),
    ('Remedy', 'Remedy'),
    ('CA ServiceDesk','CA ServiceDesk'),
    ('EHelpline', 'EHelpline'),
    ('Microsoft SCSM','Microsoft SCSM'),
)
SourceToolName=models.CharField(max_length=30,choices=SOURCE_TOOLS)

class Modules(models.Model):

ModuleName=models.CharField(max_length=30)

class DealSize(models.Model):

DEAL_SIZE=(
    ('<5 mn.','less than 5mn'),
    ('>5 mn.','greater than 5 million'),
)
DealSize=models.CharField(default="<5 mn",max_length=30,choices=DEAL_SIZE)

Creating Opportunity Class

class Opportunity(models.Model):

OppName=models.CharField(max_length=100)
SetUpType=models.ForeignKey(SetUpType,on_delete=models.CASCADE)
SourceTool=models.ForeignKey(SourceTool,on_delete=models.CASCADE)
NumOfUsers=models.IntegerField(blank=True)
NumOfTools=models.IntegerField(blank=True)
Modules=models.ForeignKey(Modules,on_delete=models.CASCADE)
DealSize=models.ForeignKey(DealSize,on_delete=models.CASCADE)
ContractTimeFrame=models.IntegerField(blank=True)
SupportMonths=models.IntegerField(blank=True)
Pricing=models.CharField(max_length=50)
RLS=models.CharField(max_length=50)

The SetUpType, SourceTool,Modules and DealSize tables already contain data and the corresponding data of these tables will be displayed in dropdown for respective fields in the below form:

forms.py:

class PreReqForm(forms.ModelForm):

MODULE_NAMES = (
    ('Incident Management', 'IM'),
    ('Requset for Service', 'SR'),
    ('Problem Management', 'PM'),
    ('Change Management', 'CM'),
)
OppName=forms.CharField(label="Opportunity Name")
setUpTypel1 = SetUpType.objects.all()
setUpTypel2 = [('-----', '-----'),]
for k in setUpTypel1:
    setUpTypel2.append((k.SetUpType, k.SetUpType))
SetUpType=forms.ChoiceField(choices=setUpTypel2,label="Set-up Type")

sourceToolL1 = SourceTool.objects.all()
sourceToolL2 = [('-----', '-----'), ]
for m in sourceToolL1:
    sourceToolL2.append((m.SourceToolName, m.SourceToolName))
SourceTool=forms.ChoiceField(choices=sourceToolL2,label="Source Tool")

NumOfUsers=forms.IntegerField(label="Number of Users")
NumOfTools=forms.IntegerField(label="Number of Tools")
Modules = forms.MultipleChoiceField(choices=MODULE_NAMES, widget=forms.SelectMultiple())
dealSizel1 = DealSize.objects.all()
#dUnique=dealSizel1.distinct('DealSize')
dealSizel2 = [('-----', '-----'), ]
for m in dealSizel1:
    dealSizel2.append((m.DealSize, m.DealSize))
DealSize=forms.ChoiceField(choices=dealSizel2,label="Deal Size")
ContractTimeFrame=forms.IntegerField(label="Contract Time Frame",widget=forms.NumberInput(attrs={'placeholder': 'In Years'}))
#SupportMonths=forms.IntegerField(label="Support Months")

class Meta:
    model = Opportunity
    fields=('OppName','SetUpType','SourceTool','NumOfUsers','NumOfTools','Modules','DealSize','ContractTimeFrame',)
    exclude = ('Pricing','RLS','SupportMonths')

Views.py:

def preform(request):

if request.method == "POST":
    form = PreReqForm(request.POST)
    print request.method
    print request.POST
    print form.errors
    #print request.POST.get['SetUpType']
    if form.is_valid():
        print "valid"
        setuptype=SetUpType(SetUpType=request.POST.get['SetUpType'])
        setuptype.save()
        Opportunity.SetUpType=setuptype

        Opportunity.save()
        return redirect('preDetails')
    else:
        print "invalid"
else:
    form = PreReqForm()

return render(request, "Prerequisites/PreReq1.html", {'form': form})

Image of the form

After submitting the form i am getting this on console:
POST

The error is:

ValueError: Cannot assign "u'Shared'": "Opportunity.SetUpType" must be a "SetUpType" instance.
  It is not printing form.errors and form.is_valid() also.

Please help. Thanks in advance.