1
I followed the steps and just copied the programming from the google website. I made a button, that it checks the connection with my network, through the IP and Port, when clicking the button, if it has connection with the network, it shows a Toast with error message, and if there is connection it edits the text field of the screen of the app. I followed the steps of this link: http://developer.android.com/intl/pt-br/training/basics/network-ops/connecting.html My problem, is that by clicking the button, the application closes and the android returns the message "Unfortunately the app stopped".
Below is the source code.
Mainactivity.java
package start.home.app;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
Button btnSolicitar;
EditText editResultado;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSolicitar=(Button)findViewById(R.id.btnSolicitar);
btnSolicitar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String stringUrl = "192.168.0.1:8080/teste.html";
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new DownloadWebpageTask().execute(stringUrl);
} else {
Toast.makeText(getApplicationContext(), "Nenhuma Conexão Encontrada!", Toast.LENGTH_LONG).show();
}
}
});
}
private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
try {
Conexao conexao = new Conexao();
return conexao.downloadUrl(urls[0]);
} catch (IOException e) {
return "Servidor Não Encontrado!";
}
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String resultado) {
// textView.setText(result);
editResultado.setText(resultado);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Java connection.
package start.home.app;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
public class Conexao {
// Given a URL, establishes an HttpUrlConnection and retrieves
// the web page content as a InputStream, which it returns as
// a string.
public String downloadUrl(String myurl) throws IOException {
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
// Reads an InputStream and converts it to a String.
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
}
I added permissions to Androidmanifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
When emulating normally, logcat looks like this.
12-29 22:50:01.357: D/HyLog(32639): I : /data/font/config/sfconfig.dat, No such file or directory (2)
12-29 22:50:01.357: D/HyLog(32639): I : /data/font/config/dfactpre.dat, No such file or directory (2)
12-29 22:50:01.357: D/HyLog(32639): I : /data/font/config/sfconfig.dat, No such file or directory (2)
12-29 22:50:01.547: D/BubblePopupHelper(32639): isShowingBubblePopup : false
12-29 22:50:01.627: I/Adreno-EGL(32639): <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_KK_3.5_RB1.04.04.02.006.089_msm8610_KK_3.5_RB1__release_AU ()
12-29 22:50:01.627: I/Adreno-EGL(32639): OpenGL ES Shader Compiler Version: E031.24.00.06
12-29 22:50:01.627: I/Adreno-EGL(32639): Build Date: 01/30/14 Thu
12-29 22:50:01.627: I/Adreno-EGL(32639): Local Branch:
12-29 22:50:01.627: I/Adreno-EGL(32639): Remote Branch: quic/kk_3.5_rb1.21
12-29 22:50:01.627: I/Adreno-EGL(32639): Local Patches: NONE
12-29 22:50:01.627: I/Adreno-EGL(32639): Reconstruct Branch: AU_LINUX_ANDROID_KK_3.5_RB1.04.04.02.006.089 + NOTHING
12-29 22:50:01.727: D/OpenGLRenderer(32639): Enabling debug mode 0
12-29 22:50:01.757: D/BubblePopupHelper(32639): isShowingBubblePopup : false
12-29 22:50:01.757: D/BubblePopupHelper(32639): isShowingBubblePopup : false
12-29 22:50:01.787: D/BubblePopupHelper(32639): isShowingBubblePopup : false
12-29 22:50:01.787: D/BubblePopupHelper(32639): isShowingBubblePopup : false
12-29 22:50:01.837: I/ActivityManager(32639): Timeline: Activity_idle id: android.os.BinderProxy@4246c860 time:17786129
After I click the button, these messages appear in the logcat.
12-29 22:50:16.187: I/ViewRootImpl(32639): ViewRoot's Touch Event : ACTION_DOWN
12-29 22:50:16.197: I/ViewRootImpl(32639): ViewRoot's Touch Event : ACTION_UP
12-29 22:50:16.257: D/AndroidRuntime(32639): Shutting down VM
12-29 22:50:16.257: W/dalvikvm(32639): threadid=1: thread exiting with uncaught exception (group=0x41e85e90)
12-29 22:50:16.267: E/AndroidRuntime(32639): FATAL EXCEPTION: main
12-29 22:50:16.267: E/AndroidRuntime(32639): Process: start.home.app, PID: 32639
12-29 22:50:16.267: E/AndroidRuntime(32639): java.lang.NullPointerException
12-29 22:50:16.267: E/AndroidRuntime(32639): at start.home.app.MainActivity$DownloadWebpageTask.onPostExecute(MainActivity.java:66)
12-29 22:50:16.267: E/AndroidRuntime(32639): at start.home.app.MainActivity$DownloadWebpageTask.onPostExecute(MainActivity.java:1)
12-29 22:50:16.267: E/AndroidRuntime(32639): at android.os.AsyncTask.finish(AsyncTask.java:632)
12-29 22:50:16.267: E/AndroidRuntime(32639): at android.os.AsyncTask.access$600(AsyncTask.java:177)
12-29 22:50:16.267: E/AndroidRuntime(32639): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
12-29 22:50:16.267: E/AndroidRuntime(32639): at android.os.Handler.dispatchMessage(Handler.java:102)
12-29 22:50:16.267: E/AndroidRuntime(32639): at android.os.Looper.loop(Looper.java:136)
12-29 22:50:16.267: E/AndroidRuntime(32639): at android.app.ActivityThread.main(ActivityThread.java:5118)
12-29 22:50:16.267: E/AndroidRuntime(32639): at java.lang.reflect.Method.invokeNative(Native Method)
12-29 22:50:16.267: E/AndroidRuntime(32639): at java.lang.reflect.Method.invoke(Method.java:515)
12-29 22:50:16.267: E/AndroidRuntime(32639): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
12-29 22:50:16.267: E/AndroidRuntime(32639): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:606)
12-29 22:50:16.267: E/AndroidRuntime(32639): at dalvik.system.NativeStart.main(Native Method)
If necessary, I can download the project. Or even the app apk file.