0

On Gingerbread 2.3,my application can run and can connect to server.

But on ICS 4.0.4, can run but can't to connect to server. I can connect to server on browser on ICS.

What is cause and how to solve it.

public class NFC_readerActivity extends Activity {

private NfcAdapter mAdapter;
private PendingIntent mPendingIntent;
private NdefMessage mNdefPushMessage;
private AlertDialog mDialog;

// New methods in Android 2.3.3
private static Method sAdapter_enableForegroundDispatch;
private static Method sAdapter_enableForegroundNdefPush;
private static Method sAdapter_disableForegroundDispatch;
private static Method sAdapter_disableForegroundNdefPush;

final static String url = "http://10.204.3.112/getpos.php";
static String result = "0";
String a = "";

static {
    try {
        sAdapter_enableForegroundDispatch = NfcAdapter.class.getMethod(
                "enableForegroundDispatch", new Class[] { Activity.class,
                        PendingIntent.class, IntentFilter[].class,
                        String[][].class });
        sAdapter_enableForegroundNdefPush = NfcAdapter.class.getMethod(
                "enableForegroundNdefPush", new Class[] { Activity.class,
                        NdefMessage.class });
        sAdapter_disableForegroundDispatch = NfcAdapter.class
                .getMethod("disableForegroundDispatch",
                        new Class[] { Activity.class });
        sAdapter_disableForegroundNdefPush = NfcAdapter.class
                .getMethod("disableForegroundNdefPush",
                        new Class[] { Activity.class });
    } catch (NoSuchMethodException e) {
        // failure, i.e Android 2.3-2.3.2
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    boolean checkConnect = isConnectedToServer(url, 30000);
    if(checkConnect){
        Toast.makeText(getApplicationContext(), "connected",
                Toast.LENGTH_SHORT).show();
    }else{
        Toast.makeText(getApplicationContext(), "not connect",
                Toast.LENGTH_SHORT).show();
    }
    resolveIntent(getIntent());

    mDialog = new AlertDialog.Builder(this).setNeutralButton("Ok", null)
            .create();

    mAdapter = NfcAdapter.getDefaultAdapter(this);
    if (mAdapter == null) {
        showMessage(R.string.error, R.string.no_nfc);
    }

    mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
            getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
    mNdefPushMessage = new NdefMessage(new NdefRecord[] { newTextRecord(
            "Message from NFC Reader :-)", Locale.ENGLISH, true) });
}

private void showMessage(int title, int message) {
    mDialog.setTitle(title);
    mDialog.setMessage(getText(message));
    mDialog.show();
}

private NdefRecord newTextRecord(String text, Locale locale,
        boolean encodeInUtf8) {
    byte[] langBytes = locale.getLanguage().getBytes(
            Charset.forName("US-ASCII"));

    Charset utfEncoding = encodeInUtf8 ? Charset.forName("UTF-8") : Charset
            .forName("UTF-16");
    byte[] textBytes = text.getBytes(utfEncoding);

    int utfBit = encodeInUtf8 ? 0 : (1 << 7);
    char status = (char) (utfBit + langBytes.length);

    byte[] data = new byte[1 + langBytes.length + textBytes.length];
    data[0] = (byte) status;
    System.arraycopy(langBytes, 0, data, 1, langBytes.length);
    System.arraycopy(textBytes, 0, data, 1 + langBytes.length,
            textBytes.length);

    return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT,
            new byte[0], data);
}

@Override
protected void onResume() {
    super.onResume();
    if (mAdapter != null) {
        if (!mAdapter.isEnabled()) {
            showMessage(R.string.error, R.string.nfc_disabled);
        }
        try {
            sAdapter_enableForegroundDispatch.invoke(mAdapter, this,
                    mPendingIntent, null, null);
            sAdapter_enableForegroundNdefPush.invoke(mAdapter, this,
                    mNdefPushMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

@Override
protected void onPause() {
    super.onPause();
    if (mAdapter != null) {
        try {
            sAdapter_disableForegroundDispatch.invoke(mAdapter, this);
            sAdapter_disableForegroundNdefPush.invoke(mAdapter, this);
        } catch (Exception e) {
            // ignore
        }
    }
}

private void resolveIntent(Intent intent) {
    String action = intent.getAction();
    if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
            || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
        Parcelable[] rawMsgs = intent
                .getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        NdefMessage[] msgs;

        msgs = new NdefMessage[rawMsgs.length];
        for (int i = 0; i < rawMsgs.length; i++) {
            msgs[i] = (NdefMessage) rawMsgs[i];
        }

        getCode(msgs);
    }
}

public boolean isConnectedToServer(String url, int timeout) {
    try {
        URL myUrl = new URL(url);
        URLConnection connection = myUrl.openConnection();
        connection.setConnectTimeout(timeout);
        connection.connect();
        return true;
    } catch (Exception e) {
        return false;
    }
}


private static void getCodeServer(final String key) {
    Thread thread = new Thread() {

        public void run() {

            Looper.prepare();
            DefaultHttpClient client = new DefaultHttpClient();
            HttpParams params = client.getParams();
            HttpConnectionParams.setConnectionTimeout(params, 10000);
            HttpConnectionParams.setSoTimeout(params, 10000);
            HttpClientParams.setRedirecting(params, false);

            HttpPost post = new HttpPost(url);

            List<NameValuePair> valuePairs = new ArrayList<NameValuePair>(1);
            valuePairs.add(new BasicNameValuePair("code", key));

            try {
                post.setEntity(new UrlEncodedFormEntity(valuePairs));

            } catch (UnsupportedEncodingException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (Exception e) {
                Log.e("log_tag", "Error in http connection" + e.toString());
            }

            HttpResponse response = null;
            try {

                response = client.execute(post);
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                response.getEntity().writeTo(output);
                result = output.toString();

                client.getConnectionManager().shutdown();

            } catch (ClientProtocolException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            Looper.loop();

        }

    };

    thread.start();

    try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

void getCode(NdefMessage[] msgs) {
    if (msgs == null || msgs.length == 0) {
        return;
    }

    List<ParsedNdefRecord> records = MsgParser.parse(msgs[0]);
    Toast.makeText(getApplicationContext(), TextRecord.tRecord,
            Toast.LENGTH_SHORT).show();

    if (isConnectedToServer(url, 10000000)) {
        Toast.makeText(getApplicationContext(), "Connected.",
                Toast.LENGTH_SHORT).show();
        getCodeServer(TextRecord.tRecord);
        if (result.equals("1")) {
            Toast.makeText(getApplicationContext(), "You are teacher.",
                    Toast.LENGTH_SHORT).show();
        } else if (result.equals("2")) {
            Toast.makeText(getApplicationContext(), "You are staff.",
                    Toast.LENGTH_SHORT).show();
        } else if (result.equals("3")) {
            Toast.makeText(getApplicationContext(), "You are student.",
                    Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getApplicationContext(), "Somtring wrong.",
                    Toast.LENGTH_SHORT).show();
        }
    } else {
        Toast.makeText(getApplicationContext(), "not Connect.",
                Toast.LENGTH_SHORT).show();
    }

}

@Override
public void onNewIntent(Intent intent) {
    setIntent(intent);
    resolveIntent(intent);
}

}

Logcat has one orange line and the other line is green and blue

W/InputManagerService(132): Starting input on non-Focused client com.android.internal.view.IInputMethodClient$Stub$Proxy@417ef6e)(uid=10026 pid=1160)

Help me please, this is my Senior project. I will present tomorrow.

Name is Nilay
  • 2,743
  • 4
  • 35
  • 77
Pack Man
  • 1
  • 2

1 Answers1

1

I suspect you are connecting to the server on the UI thread and getting a NetworkOnMainThreadException. You can verify this by looking at your logs in the LogCat view. If this is the case, you should instead do it asynchronously on a background thread.

kabuko
  • 36,028
  • 10
  • 80
  • 93
  • Using an AsyncTask is probably the easiest way to do this BTW. – Yusuf X May 12 '12 at 08:11
  • Highly likely, this exception didn't exist in 2.3 see http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html – NickT May 12 '12 at 09:52