I'm developing an android aplication using a webservice in php.
Everything was working until now.
To comunicate android and php I'm using the volley library, and everything is working but this.
I don't know if it is something such a maximum number of parameters or what.
Anything is truly null,
I've test something, when I send half the parameters it "works", it returns me error 500, but at least it sends something.
When I try to send all the parameters, this weird error shows up.
here is my code, and the error:
public void inserePagamento(final Context ctx, DocTed docTed,
final ProgressDialog ringProgressDialog) {
String url = "http://192.168.1.168/declabank/ws/public/transacaoDocTed";
Encriptador cesar = Encriptador.getInstance();
HashMap<String, String> params = new HashMap<String, String>();
params.put("agencia", usuario.getAgencia());
params.put("conta", usuario.getConta());
params.put("cripto",cesar.encriptar(cesar.getChave(), usuario.getNome()));
params.put("docFavorecidoNome", docTed.getNomeFav());
params.put("docFavorecidoCompensacao", docTed.getCodComp());
params.put("docFavorecidoBanco", docTed.getCodBanco());
params.put("docFavorecidoAgencia", docTed.getnAgencia());
params.put("docFavorecidoConta", docTed.getnConta());
params.put("docFavorecidoCPFCNPJ", docTed.getCpfCnpj());
params.put("docFavorecidoTipo", docTed.getDocFTipo());
params.put("docTed", "" + docTed.getDocTed());
params.put("docFinalidadeTransacao", docTed.getFinalidadeCod());
params.put("docTitularidade", docTed.getTipoDoc());
params.put("docValor", docTed.getValor());
params.put("docData", docTed.getData());
params.put("docRemetenteNome", docTed.getNomeRemetente());
params.put("docRemetenteCPFCNPJ", docTed.getCpfCnpjRemetente());
params.put("docRemetenteConta", docTed.getContaRemetente());
params.put("CXC_COD_CX", docTed.getCodCx());
params.put("docOrigem", docTed.getOrigem());
params.put("docStatus", "" + docTed.getStatus());
params.put("docComprovante", docTed.getComprovante());
params.put("docTransferirEm", docTed.getTransferirEm());
params.put("docAgendado", "" + docTed.getAgendado());
RequestQueue rq = Volley.newRequestQueue(ctx);
DeclaJSONArrayRequest djson = new DeclaJSONArrayRequest(Method.POST,
url, params, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray responseArray) {
try {
JSONObject response = responseArray
.getJSONObject(0);
try {
Log.e("DocTed", "DocTed gravado");
Log.e("DocTed", "DocTed gravado");
Log.e("DocTed", "DocTed gravado");
Log.e("DocTed", "DocTed gravado");
Log.e("DocTed", "DocTed gravado");
String erro = response.getString("erro");
ringProgressDialog.dismiss();
Toast.makeText(ctx, erro, Toast.LENGTH_LONG)
.show();
} catch (JSONException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error != null) {
Toast.makeText(ctx, "Erro: ", Toast.LENGTH_LONG)
.show();
Log.e("Erro", "" + error.getMessage());
} else {
Toast.makeText(ctx, "Erro: " + error.getMessage(),
Toast.LENGTH_LONG).show();
Log.e("Erro", "Treta da Grossa");
}
}
});
djson.setTag("TagPagamento");
djson.setRetryPolicy((RetryPolicy) new DefaultRetryPolicy(15000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
rq.add(djson);
}
error:
11-25 11:46:17.556: E/Volley(4874): [404] NetworkDispatcher.run: Unhandled exception java.lang.NullPointerException
11-25 11:46:17.556: E/Volley(4874): java.lang.NullPointerException
11-25 11:46:17.556: E/Volley(4874): at libcore.net.UriCodec.encode(UriCodec.java:132)
11-25 11:46:17.556: E/Volley(4874): at java.net.URLEncoder.encode(URLEncoder.java:57)
11-25 11:46:17.556: E/Volley(4874): at com.android.volley.Request.encodeParameters(Request.java:463)
11-25 11:46:17.556: E/Volley(4874): at com.android.volley.Request.getBody(Request.java:449)
11-25 11:46:17.556: E/Volley(4874): at com.android.volley.toolbox.HurlStack.addBodyIfExists(HurlStack.java:236)
11-25 11:46:17.556: E/Volley(4874): at com.android.volley.toolbox.HurlStack.setConnectionParametersForRequest(HurlStack.java:210)
11-25 11:46:17.556: E/Volley(4874): at com.android.volley.toolbox.HurlStack.performRequest(HurlStack.java:106)
11-25 11:46:17.556: E/Volley(4874): at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:96)
11-25 11:46:17.556: E/Volley(4874): at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:110)
11-25 11:46:21.496: E/Erro(4874): java.lang.NullPointerException
you will get this exception, when the any of the params value is null.
Check your value parameters in params.
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I use a OnClickListener to execute a method this way :
b= (Button) findViewById(R.id.b);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (on){
try {sendData("b");} catch (IOException e) {e.printStackTrace();}
}
else {Toast.makeText(getApplicationContext(), "You should turn bluetooth on!", Toast.LENGTH_SHORT).show();}
}
});
sendData method :
public void sendData(String s) throws IOException {
try {
byte[] byteString = s.getBytes();
outputStream.write(byteString);
outputStream.flush();
Toast.makeText(getApplicationContext(), s + "sent", Toast.LENGTH_SHORT).show();
}catch (IOException e) {
Toast.makeText(getApplicationContext(), s + "not sent", Toast.LENGTH_SHORT).show();
e.printStackTrace();}
}
this makes my app crashes if on = true
03-28 08:37:09.733 28841-28841/com.android.map.brasrobotique
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.android.map.brasrobotique, PID: 28841
java.lang.NullPointerException
at
com.android.map.brasrobotique.MainActivity.sendData(MainActivity.java:221)
at
com.android.map.brasrobotique.MainActivity$2.onClick(MainActivity.java:77)
at android.view.View.performClick(View.java:4633)
at android.view.View$PerformClick.run(View.java:19270)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5602)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
how to prevent it from exiting?
thank you!
Try :
b= (Button) findViewById(R.id.b);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (on){
try {sendData("b");} catch (IOException | NullPointerException e) {e.printStackTrace();}
}
else {Toast.makeText(getApplicationContext(), "You should turn bluetooth on!", Toast.LENGTH_SHORT).show();}
}
});
This will catch NullPointerException and IOException
You're just catching IOExceptions. Catch any Exception and it should work. I suspect that your outputStream is null.
I am getting this error my code is, can anyone help please
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
new FetchAddressTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, Constants.USER_CURRENT_LOCATION);
else
new FetchAddressTask().execute(Constants.USER_CURRENT_LOCATION);
class FetchAddressTask extends AsyncTask<LatLng, String, String> {
#Override
protected void onPreExecute() {
// showDialog();
// showMyDialog();
DialogHelper.showTrasparentDialog(EnterBikeInfoActivity.this);
super.onPreExecute();
}
#Override
protected String doInBackground(LatLng... latLngs) {
String result = getCurrentLocationViaJSON(latLngs[0].latitude, latLngs[0].longitude);
if (result == null)
result = "";
return result;
}
#Override
protected void onPostExecute(String result) {
if (result == null || result.length() == 0) {
DialogHelper.showDialogMessage(BikeApp.getInstance(), "Unable to retrieve the address.");
} else {
addressEditText.setText(result);
}
DialogHelper.dismissTransparentDialog();
super.onPostExecute(result);
}
}
public String getCurrentLocationViaJSON(double lat, double lng) {
JSONObject jsonObj = getLocationInfo(lat, lng);
Log.i("JSON string =>", jsonObj.toString());
String currentLocation = "testing";
// String street_address = null;
// String postal_code = null;
try {
String status = jsonObj.getString("status").toString();
Log.i("status", status);
if (status.equalsIgnoreCase("OK")) {
JSONArray results = jsonObj.getJSONArray("results");
int i = 0;
Log.i("i", i + "," + results.length()); // TODO delete this
JSONObject r0 = results.getJSONObject(i);
String v = r0.getString("formatted_address");
currentLocation = v;
Log.i("JSON Geo Locatoin =>", currentLocation);
return currentLocation;
}
} catch (JSONException e) {
Log.e("testing", "Failed to load JSON");
e.printStackTrace();
}
return "";
}
getLocationInfo(lat, lng); funtion fetches address info from an http request, my flow is coming into FetchAddressTask doInBackground with correct address but when it return the address it give me this error message.
11-25 11:20:01.746: W/MessageQueue(2593): Handler{40664220} sending message to a Handler on a dead thread
11-25 11:20:01.746: W/MessageQueue(2593): java.lang.RuntimeException: Handler{40664220} sending message to a Handler on a dead thread
11-25 11:20:01.746: W/MessageQueue(2593): at android.os.MessageQueue.enqueueMessage(MessageQueue.java:196)
11-25 11:20:01.746: W/MessageQueue(2593): at android.os.Handler.sendMessageAtTime(Handler.java:457)
11-25 11:20:01.746: W/MessageQueue(2593): at android.os.Handler.sendMessageDelayed(Handler.java:430)
11-25 11:20:01.746: W/MessageQueue(2593): at android.os.Handler.sendMessage(Handler.java:367)
11-25 11:20:01.746: W/MessageQueue(2593): at android.os.Message.sendToTarget(Message.java:349)
11-25 11:20:01.746: W/MessageQueue(2593): at android.os.AsyncTask$3.done(AsyncTask.java:214)
11-25 11:20:01.746: W/MessageQueue(2593): at java.util.concurrent.FutureTask$Sync.innerSet(FutureTask.java:253)
11-25 11:20:01.746: W/MessageQueue(2593): at java.util.concurrent.FutureTask.set(FutureTask.java:113)
11-25 11:20:01.746: W/MessageQueue(2593): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:311)
11-25 11:20:01.746: W/MessageQueue(2593): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
11-25 11:20:01.746: W/MessageQueue(2593): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
11-25 11:20:01.746: W/MessageQueue(2593): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
11-25 11:20:01.746: W/MessageQueue(2593): at java.lang.Thread.run(Thread.java:1019)
In my Android application i am creating a pie chart using achartengine library. When click a button it takes data from sqlite database and draw a pie chart. This is my code segment.
btnpieChart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SelectDBAdapter selectDBAdapter = SelectDBAdapter
.getDBAdapterInstance(getActivity());
try {
selectDBAdapter.openDataBase();
chartDataMap = selectDBAdapter
.getPieChartData(strBusinessUnit,
currentPeriod, currentYear);
} catch (Exception e) {
selectDBAdapter.close();
e.printStackTrace();
} finally {
selectDBAdapter.close();
}
System.out.println("chartDataMap === "+ chartDataMap);
if (chartDataMap.size() > 0) {
for (Map.Entry<String, Double> entry : chartDataMap.entrySet()) {
lstBrandNames.add(entry.getKey());
lstAchievedVals.add(entry.getValue());
}
ArrayList<Double> distribution = calc_Percentage(lstAchievedVals);
System.out.println("distribution === " + distribution);
lstBrandNames = set_lables(lstBrandNames, distribution);
CategorySeries distributionSeries = new CategorySeries(
"Brands - Achievement Progress");
for (int i = 0; i < distribution.size(); i++) {
distributionSeries.add(lstBrandNames.get(i), distribution.get(i));
}
DefaultRenderer defaultRenderer = new DefaultRenderer();
defaultRenderer.setApplyBackgroundColor(true);
defaultRenderer.setBackgroundColor(Color.WHITE);
for (int i = 0; i < distribution.size(); i++) {
SimpleSeriesRenderer seriesRenderer = new SimpleSeriesRenderer();
Random rnd = new Random();
int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
seriesRenderer.setColor(color);
seriesRenderer.setGradientEnabled(false);
seriesRenderer.setDisplayChartValues(true);
seriesRenderer.setShowLegendItem(false);
defaultRenderer.setLabelsTextSize(25);
defaultRenderer.addSeriesRenderer(seriesRenderer);
}
defaultRenderer.setLabelsColor(Color.BLACK);
defaultRenderer.setChartTitle("Brands - Achievement Progress");
defaultRenderer.setChartTitleTextSize(30);
defaultRenderer.setZoomButtonsVisible(true);
defaultRenderer.setShowLabels(true);
FragmentTransaction ft = getFragmentManager().beginTransaction();
mChartView = ChartFactory.getPieChartView(getActivity(), distributionSeries, defaultRenderer);
ft.replace(mChartView.getId(), new DummySectionFragment(), "NewFragmentTag");
ft.addToBackStack(null);
ft.commit();
}
}
});
My mChartView is,
private GraphicalView mChartView = null;
Log cat says:
11-25 07:03:58.311: E/AndroidRuntime(2706): FATAL EXCEPTION: main
11-25 07:03:58.311: E/AndroidRuntime(2706): android.content.res.Resources$NotFoundException: Unable to find resource ID #0xffffffff
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.content.res.Resources.getResourceName(Resources.java:1659)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:919)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1460)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:440)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.os.Handler.handleCallback(Handler.java:725)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.os.Handler.dispatchMessage(Handler.java:92)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.os.Looper.loop(Looper.java:137)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.app.ActivityThread.main(ActivityThread.java:5039)
11-25 07:03:58.311: E/AndroidRuntime(2706): at java.lang.reflect.Method.invokeNative(Native Method)
11-25 07:03:58.311: E/AndroidRuntime(2706): at java.lang.reflect.Method.invoke(Method.java:511)
11-25 07:03:58.311: E/AndroidRuntime(2706): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
11-25 07:03:58.311: E/AndroidRuntime(2706): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
11-25 07:03:58.311: E/AndroidRuntime(2706): at dalvik.system.NativeStart.main(Native Method)
I would be much obliged if anyone could explain what's going on here and how can I solve this issue.
Thanks
Check these lines
mChartView = ChartFactory.getPieChartView(getActivity(), distributionSeries, defaultRenderer);
ft.replace(mChartView.getId(), new DummySectionFragment(), "NewFragmentTag");
especially mChartView.getId() log this value and check it with what you expected
I have a BroadcastReceiver that receives an SMS and then is supposed to immediately send a reply SMS if the text has certain characters. Now it receives and sends the SMSs but it soon forces close giving something like: Unable to start receiver... NullPointerException... ActivityThread.handleReciever (paraphrasing) in the LogCat...what might be the issue? Here's my code, you're looking for the ELSE IF statement(that's the part that I'm currently testing):
public class Service extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if (intent.getAction()
.equals("android.provider.Telephony.SMS_RECEIVED")) {
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String msgFrom;
if (bundle != null) {
try {
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++) {
String verificationCode = "717345221";
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
msgFrom = msgs[i].getOriginatingAddress();
String encodeHash = Uri.encode("#");
msgFrom = "0" + msgFrom.substring(4) + encodeHash;
String msgBody = msgs[i].getMessageBody();
if (msgBody.startsWith(verificationCode)) {
this.abortBroadcast();
msgBody = msgBody.substring(verificationCode
.length());
try {
String dial = msgBody + "*" + msgFrom;
Intent call = new Intent(Intent.ACTION_CALL,
Uri.parse("tel:" + dial));
call.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(call);
} catch (Exception e) {
e.toString();
}
} else if (msgBody.contains("TEST123")) {
Toast.makeText(context,
"TEST123 text recieved",
Toast.LENGTH_LONG).show();
String transactionCode = null;
if (msgBody.length() > 9) {
transactionCode = msgBody.substring(0, 9);
}
String attachCode = "776f76wfuh";
String number = msgs[i].getOriginatingAddress();
String message = attachCode + transactionCode;
try {
SmsManager sms = SmsManager.getDefault();
PendingIntent pi = PendingIntent.getBroadcast(
context, 0, new Intent(context,
Service.class), 0);
sms.sendTextMessage(number, null, message, pi,
null);
Toast.makeText(context,
"Text sent with attach code",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
// TODO: handle exception
Log.d("Exception caught", e.getMessage());
}
}
}
} catch (Exception e) {
Log.d("Exception caught", e.getMessage());
}
}
}
}
}
Here's the LogCat:
10-31 20:42:05.269: E/AndroidRuntime(15080): FATAL EXCEPTION: main
10-31 20:42:05.269: E/AndroidRuntime(15080): java.lang.RuntimeException: Unable to start receiver com.adbionicpaymentsystem.Service: java.lang.NullPointerException
10-31 20:42:05.269: E/AndroidRuntime(15080): at android.app.ActivityThread.handleReceiver(ActivityThread.java:1805)
10-31 20:42:05.269: E/AndroidRuntime(15080): at android.app.ActivityThread.access$2400(ActivityThread.java:117)
10-31 20:42:05.269: E/AndroidRuntime(15080): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:981)
10-31 20:42:05.269: E/AndroidRuntime(15080): at android.os.Handler.dispatchMessage(Handler.java:99)
10-31 20:42:05.269: E/AndroidRuntime(15080): at android.os.Looper.loop(Looper.java:130)
10-31 20:42:05.269: E/AndroidRuntime(15080): at android.app.ActivityThread.main(ActivityThread.java:3683)
10-31 20:42:05.269: E/AndroidRuntime(15080): at java.lang.reflect.Method.invokeNative(Native Method)
10-31 20:42:05.269: E/AndroidRuntime(15080): at java.lang.reflect.Method.invoke(Method.java:507)
10-31 20:42:05.269: E/AndroidRuntime(15080): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:875)
10-31 20:42:05.269: E/AndroidRuntime(15080): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:633)
10-31 20:42:05.269: E/AndroidRuntime(15080): at dalvik.system.NativeStart.main(Native Method)
10-31 20:42:05.269: E/AndroidRuntime(15080): Caused by: java.lang.NullPointerException
10-31 20:42:05.269: E/AndroidRuntime(15080): at com.adbionicpaymentsystem.Service.onReceive(Service.java:21)
10-31 20:42:05.269: E/AndroidRuntime(15080): at android.app.ActivityThread.handleReceiver(ActivityThread.java:1794)
10-31 20:42:05.269: E/AndroidRuntime(15080): ... 10 more
be sure to have the permission in your manifest
<uses-permission android:name="android.permission.SEND_SMS"/>
and note that sendTextMessage
This method was deprecated in API level 4.
Use android.telephony.SmsManager.
Problem was I had another service running on the test device that seemingly interferes with this service
In my android application the data has to be shared using twitter so had followed this link http://androidcodeexamples.blogspot.in/2011/12/how-to-integrate-twitter-in-android.html, everything works fine, but after giving username and password, getting force close option.
here's the logcat output
01-17 17:07:54.118: E/AndroidRuntime(383): FATAL EXCEPTION: main
01-17 17:07:54.118: E/AndroidRuntime(383): java.lang.NullPointerException
01-17 17:07:54.118: E/AndroidRuntime(383): com.twitter.android.TwitterApp$1.handleMessage(TwitterApp.java:237)
01-17 17:07:54.118: E/AndroidRuntime(383): at android.os.Handler.dispatchMessage(Handler.java:99)
01-17 17:07:54.118: E/AndroidRuntime(383): at android.os.Looper.loop(Looper.java:123)
01-17 17:07:54.118: E/AndroidRuntime(383): at android.app.ActivityThread.main(ActivityThread.java:3683)
01-17 17:07:54.118: E/AndroidRuntime(383): at java.lang.reflect.Method.invokeNative(Native Method)
01-17 17:07:54.118: E/AndroidRuntime(383): at java.lang.reflect.Method.invoke(Method.java:507)
01-17 17:07:54.118: E/AndroidRuntime(383): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-17 17:07:54.118: E/AndroidRuntime(383): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-17 17:07:54.118: E/AndroidRuntime(383): at dalvik.system.NativeStart.main(Native Method)
this is the code in mainactivity
public class Singlemenuitem extends Activity {
private TwitterApp mTwitter;
private static final String CONSUMER_KEY = "6JyIkj71ZqG4wk3YF0Y4hw";
private static final String CONSUMER_SECRET = "sJl9aRVqlEt7nxlKvpMVK6tLULz5FSQ2KUOW0yie4";
private enum FROM {
TWITTER_POST, TWITTER_LOGIN
};
private enum MESSAGE {
SUCCESS, DUPLICATE, FAILED, CANCELLED
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
mTwitter = new TwitterApp(this, CONSUMER_KEY, CONSUMER_SECRET);
//share twitter
final ImageView twitter = (ImageView) findViewById(R.id.twitter);
twitter.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
mTwitter.resetAccessToken();
if (mTwitter.hasAccessToken() == true) {
try {
mTwitter.updateStatus(String.valueOf(Html
.fromHtml(TwitterApp.MESSAGE)));
// File f = new File("/mnt/sdcard/android.jpg");
// mTwitter.uploadPic(f, String.valueOf(Html
// .fromHtml(TwitterApp.MESSAGE)));
postAsToast(FROM.TWITTER_POST, MESSAGE.SUCCESS);
} catch (Exception e) {
if (e.getMessage().toString().contains("duplicate")) {
postAsToast(FROM.TWITTER_POST, MESSAGE.DUPLICATE);
}
e.printStackTrace();
}
mTwitter.resetAccessToken();
} else {
mTwitter.authorize();
}
}
private void postAsToast(FROM twitterPost, MESSAGE success) {
switch (twitterPost) {
case TWITTER_LOGIN:
switch (success) {
case SUCCESS:
Toast.makeText(Singlemenuitem.this, "Login Successful", Toast.LENGTH_LONG)
.show();
break;
case FAILED:
Toast.makeText(Singlemenuitem.this, "Login Failed", Toast.LENGTH_LONG).show();
default:
break;
}
break;
case TWITTER_POST:
switch (success) {
case SUCCESS:
Toast.makeText(Singlemenuitem.this, "Posted Successfully", Toast.LENGTH_LONG)
.show();
break;
case FAILED:
Toast.makeText(Singlemenuitem.this, "Posting Failed", Toast.LENGTH_LONG)
.show();
break;
case DUPLICATE:
Toast.makeText(Singlemenuitem.this,
"Posting Failed because of duplicate message...",
Toast.LENGTH_LONG).show();
default:
break;
}
break;
}
TwDialogListener mTwLoginDialogListener = new TwDialogListener() {
public void onError(String value) {
postAsToast(FROM.TWITTER_LOGIN, MESSAGE.FAILED);
Log.e("TWITTER", value);
mTwitter.resetAccessToken();
}
public void onComplete(String value) {
try {
mTwitter.updateStatus(TwitterApp.MESSAGE);
postAsToast(FROM.TWITTER_POST, MESSAGE.SUCCESS);
} catch (Exception e) {
if (e.getMessage().toString().contains("duplicate")) {
postAsToast(FROM.TWITTER_POST, MESSAGE.DUPLICATE);
}
e.printStackTrace();
}
mTwitter.resetAccessToken();
}