Pass SSL Layer trusted certificates - android

Guys here is my code please review it because it gives NullPointerException on the line conn.setSSLSocketFactory(sslContext.getSocketFactory());........
Code:
package com.halosys.TvAnyTime;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.crypto.NullCipher;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.protocol.HTTP;
import android.app.Activity;
import android.content.res.Resources.NotFoundException;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class HomeScreen extends Activity {
StringEntity entry;
BasicHttpResponse httpResponse;
BufferedReader in = null;
//protected KeyStore sslContext;
KeyStore ksTrust;
TrustManagerFactory tmf;
SSLContext sslContext;
URL url;
HttpsURLConnection conn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button closeButton = (Button)this.findViewById(R.id.button1);
closeButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Load the self-signed server certificate
try {
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier(){
public boolean verify(String hostname, SSLSession session) {
return true;
}});
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new X509TrustManager[]{new X509TrustManager(){
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {}
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}}}, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(
context.getSocketFactory());
} catch (Exception e) { // should never happen
e.printStackTrace();
}
char[] passphrase = "ssltestcert".toCharArray();
try {
ksTrust = KeyStore.getInstance("BKS");
} catch (KeyStoreException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
ksTrust.load(getApplicationContext().getResources().openRawResource(R.raw.ssltestcert),
passphrase);
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (CertificateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (NotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
tmf = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
tmf.init(ksTrust);
} catch (KeyStoreException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Create a SSLContext with the certificate
/*try {
sslContext = SSLContext.getInstance("TLS");
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
sslContext.init(null, tmf.getTrustManagers(), new SecureRandom());
} catch (KeyManagementException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}*/
// Create a HTTPS connection
try {
url = new URL("https", "https://50.18.49.118/xmlrpcand", 443, "/ssltest");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
conn = (HttpsURLConnection) url.openConnection();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
/* Uncomment the following line of code if you want to skip SSL */
/* hostname verification. But it should only be done for testing. */
/* See http://randomizedsort.blogspot.com/2010/09/programmatically-disabling-java-ssl.html */
// conn.setHostnameVerifier((HostnameVerifier) new NullCipher());
//conn.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
conn.setSSLSocketFactory(sslContext.getSocketFactory());
//MyHttpClient obj= new MyHttpClient(HomeScreen.this);
//obj.createClientConnectionManager();
/* HttpClient httpclient = new DefaultHttpClient();
String str2= "<?xml version=\"1.0\"?><methodCall><methodName>tva1.catalog.version</methodName><params></params></methodCall>";
HttpPost httppost = new HttpPost("https://50.18.49.118/xmlrpcand");
try {
entry = new StringEntity(str2,HTTP.UTF_8);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
entry.setContentType("text/xml");
httppost.setHeader("Content-Type","application/soap+xml;charset=UTF-8");
httppost.setEntity(entry);
try {
httpResponse = (BasicHttpResponse) httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
try {
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String result = sb.toString(); //Responsed xml is stored in result
System.out.print(result);
}
*/ };
});
}
}

Does it print a stack trace just before throwing the exception? If url.openConnection() fails, it throws IOException, but all you're doing to handle that is to print the stack trace. I'd expect problems if you try to use conn after that happens.

Related

AsyncTask Execute method showing error

I am trying to call execute method of a GetMethodExample class which has extended AsyncTask, but it is showing me the error that the method execute is undefined for the GetMethodExapmle. Here is my code.
GetMethodExample.java:
package com.shehryar.httpclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.AsyncTask;
public class GetMethodExample extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
BufferedReader in = null;
String data = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
URI website= new URI(params[0]);
request.setURI(website);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.seperator");
while ((l = in.readLine()) != null) {
sb.append(l + nl);
}
in.close();
data = sb.toString();
return data;
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
return data;
} catch (Exception e) {
{
e.printStackTrace();
}
}
}
}
return null;
}
}
//MainActivity
HttpExample.java:
package com.shehryar.httpclient;
import java.util.concurrent.ExecutionException;
import com.shehryar.httpclient.R.layout;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HttpExample extends Activity {
TextView httpstuff;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.httpex);
httpstuff=(TextView) findViewById(R.id.tvhttp);
String data;
String website="http://www.google.com";
String extra="";
try {
GetMethodExample obj= new GetMethodExample();
data=obj.execute(website).get(); //Here is the error
httpstuff.setText(data);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
httpstuff.setText("Error:" + e.toString());
} catch (ExecutionException e) {
// TODO Auto-generated catch block
httpstuff.setText("Error:" + e.toString());
}
}
}
data=obj.execute(website).get(); //Here is the error
You are trying to get the data synchronously from an AsyncTask.
First, you start the task:
obj.execute(website);
Then you override onPostExecute() in your AsyncTask to handle the finish:
#Override
public void onPostExecute(String data) {
httpstuff.setText(data);
}
Now somehow you have to give the AsyncTask a reference to your Activity or your TextView so that you can update the UI in onPostExecute().
Go read the reference docs on AsyncTask to understand how the threads interact and which methods run on which thread.
AsyncTask | Android Developers
Thanks to Kris Larson for reply but I got my code working just after restarting eclipse. My code was fine but it was eclipse that was making problems

Filter log information, BufferedWriter in-file invalid

I have a log package.I want to filter the log.e, and save it to another file. But I find BufferedWriter can not reach the expected effect. Such as the two lines in log file below can not store another file.
E/Vold ( 96): Sleep 2s to make sure that coldboot() events are handled
E/WindowManager( 244): setEventDispatching false
attach code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LogSpider {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader("C:\\Users\\Administrator\\Desktop\\log.txt"));
String line = "";
try {
while((line = bufferedReader.readLine())!=null)
{
Parseelog(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
bufferedReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void Parseelog(String line)
{
BufferedWriter bufferedWriter = null;
try {
bufferedWriter = new BufferedWriter(new FileWriter("C:\\Users\\Administrator\\Desktop\\logspider2.txt"));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//Pattern pattern = Pattern.compile("[\\w[.-]]+\\#[\\w[.-]]{2,}\\.[\\w[.-]]+");
Pattern pattern = Pattern.compile("^E.*");
Matcher matcher = pattern.matcher(line);
while(matcher.find())
{
String string = new String(matcher.group());
string += "\n";
System.out.println(string); //here can print the search results
try {
bufferedWriter.write(string, 0, string.length());
bufferedWriter.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
bufferedWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
The problem with you code was that you where opening the logspider2.txt file every time you want to write the matching line. So it was overwriting all the previous data. To solve the issue you need to open your file in the append mode as follows:
bufferedWriter = new BufferedWriter(
new FileWriter(
"F:\\praful\\androidworkspace_2\\Test\\src\\logspider2.txt",true));
I tried you code and made some modification to make it work. Following is the working code:
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(
"F:\\praful\\androidworkspace_2\\Test\\src\\logs.txt"));
String line = "";
try {
while ((line = bufferedReader.readLine()) != null) {
Parseelog(line);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
bufferedReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void Parseelog(String line) {
BufferedWriter bufferedWriter = null;
// Pattern pattern =
// Pattern.compile("[\\w[.-]]+\\#[\\w[.-]]{2,}\\.[\\w[.-]]+");
Pattern pattern = Pattern.compile("^E.*");
Matcher matcher = pattern.matcher(line);
try {
bufferedWriter = new BufferedWriter(
new FileWriter(
"F:\\praful\\androidworkspace_2\\Test\\src\\logspider2.txt",true));
while (matcher.find()) {
String string = new String(matcher.group());
string += "\n";
System.out.println(string); // here can print the search results
bufferedWriter.write(string);
}
bufferedWriter.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Please changed the file path to your local paths. Hope it help you..

Android TCP Smartphone to PC with USB no wifi

Hi I have managed some code but its not working
I want to control send message from PC To Android over my application via USB not by WIFI
i tried this code
But it's giving me error that
07-13 20:08:28.530: W/System.err(8990): java.net.ConnectException: localhost/127.0.0.1:383 - Connection refused
I have done port forward by adb
For Desktop
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class comunicate {
public static void main(String[] args){
ServerSocket serverSocket = null;
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
serverSocket = new ServerSocket(383);
System.out.println("Listening :8888");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(true){
try {
socket = serverSocket.accept();
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
System.out.println("ip: " + socket.getInetAddress());
System.out.println("message: " + dataInputStream.readUTF());
dataOutputStream.writeUTF("Hello!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if( socket!= null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if( dataInputStream!= null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if( dataOutputStream!= null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
For Mobile
package demo.app.org;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class DemoAppActivity extends Activity {
EditText textOut;
TextView textIn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textOut = (EditText)findViewById(R.id.textout);
Button buttonSend = (Button)findViewById(R.id.send);
textIn = (TextView)findViewById(R.id.textin);
buttonSend.setOnClickListener(buttonSendOnClickListener);
}
Button.OnClickListener buttonSendOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("localhost", 383);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(textOut.getText().toString());
textIn.setText(dataInputStream.readUTF());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}};
}
Isn't this code for tcp communication over wifi? I think you can not communicate with android over USB except for logcat.

Yahoo Integration in Android

I'm planning to integrate Yahoo in my Android Application to get the name and personal details of a user. How do I integrate Yahoo with android?
I have spent several hours looking for a tutorial/sample android application that integrates Yahoo login using OAuth, but I can't find one.
Look at the following code , You need Signpost library Signpost Library
import oauth.signpost.OAuth;
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 oauth.signpost.signature.HmacSha1MessageSigner;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.synapse.selfervices.R;
public class YahooScreen extends Activity {
private static final String REQUEST_TOKEN_ENDPOINT_URL ="https://api.login.yahoo.com/oauth/v2/get_request_token";
private static final String ACCESS_TOKEN_ENDPOINT_URL ="https://api.login.yahoo.com/oauth/v2/get_access_token";
private static final String AUTHORIZE_WEBSITE_URL ="https://api.login.yahoo.com/oauth/v2/request_auth";
private static final int PIN_DIALOG = 0;
String CALLBACK_URL = OAuth.OUT_OF_BAND; // this should be the same as the
// SCHEME and HOST values in
// your AndroidManifest.xml file
String CONSUMER_KEY = "";//
String CONSUMER_SECRET = "";
private CommonsHttpOAuthConsumer myConsumer;
private CommonsHttpOAuthProvider myProvider;
private String requestToken;
private String accessToken;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
callOAuth();
showDialog(PIN_DIALOG);
// createPinDialog().show();
}
private void callOAuth() {
try {
// retrieve the consumer token and then sign it
myConsumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY,
CONSUMER_SECRET);
myConsumer.setMessageSigner(new HmacSha1MessageSigner());
HttpClient client = new DefaultHttpClient();
// retrieve the provider by using the signed consumer token
myProvider = new CommonsHttpOAuthProvider(
REQUEST_TOKEN_ENDPOINT_URL, ACCESS_TOKEN_ENDPOINT_URL,
AUTHORIZE_WEBSITE_URL, client);
myProvider.setOAuth10a(true);
String aUrl = myProvider.retrieveRequestToken(myConsumer,
CALLBACK_URL);
requestToken = myConsumer.getToken();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(aUrl)));
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), ex.getMessage(),
Toast.LENGTH_LONG).show();
Log.e(ex.getMessage(), ex.toString());
}
}
// this is the callback function that will run when oauth authenticates
// successfully
#Override
protected void onNewIntent(Intent intent) {
System.out.println("OnNewIntent...");
Toast.makeText(getApplicationContext(), "OnNewIntent - It works!",
Toast.LENGTH_LONG).show();
// whatever you want to do after authenticating goes here ....
}
AlertDialog createPinDialog() {
LayoutInflater factory = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
// LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.pin, null);
final EditText pinText = (EditText) textEntryView
.findViewById(R.id.pin_text);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Twitter OAuth PIN");
builder.setView(textEntryView);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
if (pinText != null)
gotOAuthPin(pinText.getText().toString());
onResume();
}
});
return builder.create();
}
private void gotOAuthPin(String pin) {
SharedPreferences.Editor editor = getSharedPreferences("yahoo",
MODE_PRIVATE).edit();
try {
myProvider.retrieveAccessToken(myConsumer, pin);
accessToken = myConsumer.getToken();
} catch (OAuthMessageSignerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthNotAuthorizedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthCommunicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (accessToken != null && accessToken.length() > 0) {
Toast.makeText(this, "Authorized", Toast.LENGTH_SHORT).show();
HttpPost request = new HttpPost(
"http://social.yahooapis.com/v1/user/profile?format=json");
StringEntity body = null;
/*
* try { body = new StringEntity("city=hamburg&label=" +
* URLEncoder.encode("Send via Signpost!", "UTF-8")); } catch
* (UnsupportedEncodingException e1) { // TODO Auto-generated catch
* block e1.printStackTrace(); }
* body.setContentType("application/x-www-form-urlencoded");
* request.setEntity(body);
*/
try {
myConsumer.sign(request);
} catch (OAuthMessageSignerException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (OAuthMessageSignerException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (OAuthExpectationFailedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (OAuthCommunicationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("Sending update request to Fire Eagle...");
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = null;
try {
response = httpClient.execute(request);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(
this,
"Response: " + response.getStatusLine().getStatusCode()
+ " " + response.getStatusLine().getReasonPhrase(),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Not Authorized", Toast.LENGTH_SHORT).show();
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case PIN_DIALOG:
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.pin, null);
final EditText pinText = (EditText) textEntryView
.findViewById(R.id.pin_text);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("OAuth PIN");
builder.setView(textEntryView);
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
if (pinText != null)
gotOAuthPin(pinText.getText().toString());
}
});
return builder.create();
}
return super.onCreateDialog(id);
}}

Applications crashes in 3.0 but works fine in 2.3.3

Hi guys im trying to create a application that uses a socket connection i was going across some examples, the piece of code below works fine when i run it on 2.3.3 and the same crashes in 3.0.
package com.simple.client;
import android.app.Activity;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.os.Bundle;
public class SimpleClientActivity extends Activity {
EditText textOut;
TextView textIn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textOut = (EditText)findViewById(R.id.textout);
Button buttonSend = (Button)findViewById(R.id.send);
textIn = (TextView)findViewById(R.id.textin);
buttonSend.setOnClickListener(buttonSendOnClickListener);
}
Button.OnClickListener buttonSendOnClickListener
= new Button.OnClickListener(){
public void onClick(View arg0) {
// TODO Auto-generated method stub
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("172.16.2.172", 8899);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(textOut.getText().toString());
textIn.setText(dataInputStream.readUTF());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}};
}
I have tried all but not able to figure out what is happening,
My guess is, the error caused by StrictMode.ThreadPolicy. In android 3.0, you can't access network in the same UI thread.
Do you have multiple resource folders for your layouts? if yes, maybe you do not have its related layout.

Categories

Resources