I have a problem with connecting to internet. I want to show tbe first line in the source code of www.google.com. I coded in Java console and it run well. But when I did it in android, the textView can't not show any words.
Original Java console program:
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;
public class ReadUrl {
static public String getRespond(String request) {
try{
URL url=new URL (request);
URLConnection connection=url.openConnection();
InputStream in=new BufferedInputStream(connection.getInputStream());
Scanner scanner =new Scanner(in);
String response=scanner.nextLine();
scanner.close();
return response;
}
catch (Exception e){
return null;
}
}
public static void main(String args[]){
System.out.println (getRespond("http://www.google.com"));
}
}
In android:
File MainActivity.java:
package com.example.simpleinternet;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.os.Build;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView txtView=(TextView) findViewById(R.id.textView);
txtView.setText(getRespond("www.google.com"));
}
public String getRespond(String request) {
try{
URL url=new URL (request);
URLConnection connection=url.openConnection();
InputStream in=new BufferedInputStream(connection.getInputStream());
Scanner scanner =new Scanner(in);
String response=scanner.nextLine();
scanner.close();
return response;
}
catch (IOException e){
return null;
}
}
}
File AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.simpleinternet"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.simpleinternet.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
File activity_main.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World" />
</FrameLayout>
The error is :
> 07-07 14:44:55.760: E/AndroidRuntime(4449):
> Java.lang.RuntimeException: Unable to start activity
> ComponentInfo{com.example.simpleinternet/com.example.simpleinternet.MainActivity}:
> android.os.NetworkOnMainThreadException
Sorry because I am a newbie in StackOverFlow. I will take it carefully. Can you check it for me ?
android.os.NetworkOnMainThreadException is thrown when an application attempts to perform a networking operation on its main thread.
You can run your code in AsyncTask to solve the issue.
The exception that is thrown when an application attempts to perform a networking operation on its main thread.
Please refer to below links:
What is the problem:
http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html
Why is the problem:
and
Solution:
http://developer.android.com/training/articles/perf-anr.html
How to fix android.os.NetworkOnMainThreadException?
Related
I've edited my Manifest code and my Activity code again to reflect appropriate intent filter requirements. However, I'm still getting the same results. I'm unable to read my external record, and I don't know why? When I scan my tags with the NFC Tools app, I can see everything as I would expect. My code produces a NullPointer when it attempts to "read" my array and I have no idea why?
--------------BEGIN MANIFEST--------------------
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bmt_01">
<uses-permission android:name="android.permission.NFC"/>
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-sdk android:minSdkVersion="15"/> ///must be changed in build.gradle.
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data
android:scheme="vnd.android.nfc"
android:host="ext"
android:pathPrefix="/com.example.bmt_01:externaltype"
/>
</intent-filter>
</activity>
</application>
</manifest>
--------------END MANIFEST--------------------
--------------BEGIN MAIN ACTIVITY-------------
package com.example.bmt_01;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
String currentPayload = "";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onNewIntent(Intent intent)
{
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
//added the below lines, can delete if they don't work.
NdefRecord payload = ((NdefMessage)rawMsgs[0]).getRecords()[0];
String currentPayload = new String(payload.getPayload());
if (currentPayload.equals("1"))
{
Toast.makeText(this, "NFC Scan1: " + currentPayload, Toast.LENGTH_SHORT).show();
String url = "http://www.google.com";
Intent l = new Intent(Intent.ACTION_VIEW);
l.setData(Uri.parse(url));
startActivity(l);
}
///else
///{
if (currentPayload.equals("2"))
{
Toast.makeText(this, "NFC Scan2: " + currentPayload, Toast.LENGTH_SHORT).show();
String url = "http://www.yahoo.com";
Intent l = new Intent(Intent.ACTION_VIEW);
l.setData(Uri.parse(url));
startActivity(l);
}
///}
}
protected void onResume()
{
super.onResume();
Toast.makeText(this, "NFC Scan3: ", Toast.LENGTH_SHORT).show();
enableForegroundDispatchSystem();
}
#Override
protected void onPause()
{
super.onPause();
disableForegroundDispatchSystem();
}
private void enableForegroundDispatchSystem() {
Toast.makeText(this, "NFC Scan4: ", Toast.LENGTH_SHORT).show();
}
private void disableForegroundDispatchSystem() {
Toast.makeText(this, "NFC Scan5: ", Toast.LENGTH_SHORT).show();
onNewIntent(getIntent());
}
}
--------------END MAIN ACTIVITY---------------
UPDATE*
I should add that my AAR functions correctly. When I have the above app installed on my phone, but do not have it open, my AAR automatically opens and launches the application when I scan my test tag. So, I'm able to "see" the AAR in the array, but NOT the external record.
I'm still unable to read the external record on my tag. Obviously I'm doing something wrong, but I have no idea.
You mix togerthe message and record in your for loop. However there is only one NDEF message, but this message can hold several records. You must use only rawMsgs[0]. Then your for loop can iterate over all records of that message.
I've created a library which lets you parse NDEF records.
You're on the right track - wrapping binary paylod with using the external type - the library supports plugging in your own external type parser/record type(s), if you so prefer.
Please help debug the following code
I have made sure that
1.My Device has Internet access.
2.My Android Manifest file has internet permission.
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
private StringBuilder stringBuilder = null;
private RequestQueue requestQueue;
private String url = "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=48b076c80a0b064d62117d19015db014";
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.temp);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject jsonObject = response.getJSONObject("main");
float tempr = (float) jsonObject.getDouble("temp");
stringBuilder.append(tempr);
textView.setText(stringBuilder.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage().toString(), Toast.LENGTH_LONG).show();
Log.v("Not working", error.getMessage().toString());
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonObjectRequest);
}
}
The logcat shows the following report:
java.net.UnknownHostException: Unable to resolve host
"api.openweathermap.org": No address associated with hostname
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="androidhive.com.volley5">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Faced the same issue when I was working with openweathermap API.
There are a few steps that solved my issue.
First of all, turn on emulators wifi and mobile data both.
Second, reset permission in androidmenifest.xml file. Add internet permission and also add read and write external storage.
Then run the app. Hope it will solve your error as it solved mine.
Hello.
Today I faced this problem.
There was simply no internet on the phone.
I was helped by checking the connection to Wi-Fi
I am making my first Android App, but my code produces a very strange behaviour i can't understand. And i used Google for three days now with no solution.
If i write in my AndroidManifest.xml a minSdkVersion other than "8", i can't connect to my FTP Server. Also if i use minSdkVersion "8" and targetSdkVersion other than "8". If i don't use minSdkVersion and targetSdkVersion everything works fine. In short:
min 8, target 8 = ok
min 8, no target = ok
no min, no target = ok
min 8, target 17 = failure
min 10, target 10 = failure
and so on...
Here is my AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.package"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.package.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.examplepackage.Settings"></activity>
<activity android:name="com.schmidgroup.sgfax.Tools"></activity>
<activity android:name="com.schmidgroup.sgfax.MyFTP"></activity>
<activity android:name="com.schmidgroup.sgfax.Printing"></activity>
<activity android:name="com.schmidgroup.sgfax.Listings"></activity>
<activity android:name="com.schmidgroup.sgfax.Blue"></activity>
</application>
</manifest>
My MainActivity.Java:
package com.example.package;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.content.Intent;
import android.view.MenuItem;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Button for Bluetooth-Connection
Button verbinden = (Button) findViewById(R.id.button1);
verbinden.setText(R.string.select_device);
verbinden.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent start = new Intent(getApplicationContext(), Blue.class);
startActivity(start);
}
} );
}
}
My class Blue.Java does some Bluetooth stuff and then starts Listings.Java:
package com.example.package;
import java.io.IOException;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
public class Listings extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listings);
// Connect zum FTP-Server
MyFTP conn = new MyFTP();
conn.ftpConnect(host, user, pass, 21);
[... some more FTP stuff which don't work in cause of failing Ftp Connection...]
}
}
And finally the MyFTP.Java:
package com.example.package;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.net.ftp.*;
import android.content.Context;
import android.util.Log;
public class MyFTP {
private static void showServerReply(FTPClient FTPClient) {
String[] replies = FTPClient.getReplyStrings();
if (replies != null && replies.length > 0) {
for (String aReply : replies) {
System.out.println("SERVER: " + aReply);
}
}
}
//Now, declare a public FTP client object.
private static final String TAG = "MyFTPClient";
public FTPClient mFTPClient = null;
//Method to connect to FTP server:
public boolean ftpConnect(String host, String username,
String password, int port)
{
try {
mFTPClient = new FTPClient();
// connecting to the host
mFTPClient.connect(host, port);
showServerReply(mFTPClient);
Log.i(TAG, "Successful conntected to " + host);
// now check the reply code, if positive mean connection success
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
// login using username & password
boolean status = mFTPClient.login(username, password);
Log.i(TAG, "Succesful logged in to " + host);
/* Set File Transfer Mode
*
* To avoid corruption issue you must specified a correct
* transfer mode, such as ASCII_FILE_TYPE, BINARY_FILE_TYPE,
* EBCDIC_FILE_TYPE .etc. Here, I use BINARY_FILE_TYPE
* for transferring text, image, and compressed files.
*/
mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
mFTPClient.enterLocalPassiveMode();
return status;
}
} catch(Exception e) {
Log.d(TAG, "Error: could not connect to host " + host );
}
return false;
}
[...and some more stuff...]
Can anyone see what i've doing wrong?
Thank you!
You shouldn't make any network operations on your main UI thread. watch this question about StrictMode Policy in Android 3.0 and higher.
I am creating an android application that needs to interact with a local web server(WAMP). WAMP has a php file that just echos Hello world. This application requests for this page but when I run the application and click on the button that fires the request event, there are no results printed on the EditText saying Helloworld. The following is the code:
package com.mobilevoter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLConnection;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class mobilevoter extends Activity implements OnClickListener {
Button proceed;
EditText voter_number;
EditText id_number;
URLConnection conn;
BufferedReader myreader;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
proceed=(Button)findViewById(R.id.proceed_btn);
voter_number=(EditText)findViewById(R.id.editText_voternumber);
id_number=(EditText)findViewById(R.id.editText_idnumber);
proceed.setOnClickListener(this);
}
#Override
public void onClick(View src) {
if(src==proceed){
HttpClient authenticationClient= new DefaultHttpClient();
HttpPost url_post=new HttpPost("http://10.0.2.2/practice/index.php");
HttpResponse response;
try
{
response=authenticationClient.execute(url_post);
HttpEntity authenticationEntity=response.getEntity();
InputStream authenticationStream=authenticationEntity.getContent();
BufferedReader myreader=new BufferedReader(new InputStreamReader(authenticationStream));
String inputStream;
while((inputStream=myreader.readLine())!=null)
{
voter_number.setText(inputStream);
}
}
catch(Exception exception)
{
System.out.println(exception.getMessage());
}
/*finally
{
try
{
myreader.close();
}
catch(IOException ioexception)
{
System.out.println(ioexception.getMessage());
}
}*/
}
}
}
The manifest looks like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mobilevoter"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".mobilevoter"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
I will really appreciate the help. Thanx.
Can you reach that URL from the browser app built-in the mobile/emulator?
If not, you need to check your network setup. 10.0.2.2 seems to be ok from what the guide says. Perhaps there is a firewall? Does the WAMP server listen on port 80?
http://progrium.com/localtunnel/
$ gem install localtunnel
$ localtunnel 8000
share this url:
http://xyz.localtunnel.com
You'll need RubyGems installed, but this is the easiest solution for me.
here
I uploaded my Android project made in Eclipse. The idea is that i have a service, which computes the sum of two random numbers. But when i press the OK Button, i don't see the result in that edit box... why? What i'm doing wrong? Please help
Thanks!
EDIT: The code:
//service class
package service;
import java.util.Random;
import com.android.AplicatieSuma;
import android.widget.EditText;
import android.widget.TextView;
public class ServiciuSuma
{
public ServiciuSuma() { }
public int CalculateSum()
{
Random generator=new Random();
int n=generator.nextInt();
int m=generator.nextInt();
return n+m;
}
}
The Application class:
package com.android;
import android.app.*;
import service.*;
public class ApplicationSum extends Application {
public ServiciuSuma service = new ServiciuSuma();
}
and the main Activity class:
package com.android;
import com.android.R;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuffColorFilter;
import android.graphics.drawable.Drawable;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
public class Activitate extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
View btn_ok = findViewById(R.id.btn_ok);
btn_ok.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
CalculeazaSuma();
}
});
}
private void CalculeazaSuma()
{
AplicatieSuma appState = ((AplicatieSuma)this.getApplication());
EditText txt_amount = (EditText)findViewById(R.id.txt_amount);
txt_amount.setText(appState.service.CalculateSum());
//BindData();
}
}
So that edit text does not show the sum of the random generated numbers, by the service. What's wrong?
Thanks
EDIT:
the manifest xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android"
android:versionCode="1"
android:versionName="1.0.1">
<supports-screens
android:largeScreens="true"
android:normalScreens="true"
android:smallScreens="true"
android:anyDensity="true" />
<application android:name="ApplicationSum" android:icon="#drawable/icon" android:label="#string/app_name" android:debuggable="true">
<activity android:label="#string/app_name" android:name=".Activitate">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="7" android:targetSdkVersion="7" />
</manifest>
This fix will work:
txt_amount.setText(String.valueOf(appState.service.CalculateSum()));
Without that you pass integer and android thinks it's an id of a resource to display. You should really use DDMS to identify such problems.
Have you specified in manifest that you want ApplicationSum to be used as application class?
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:name="com.android.ApplicationSum">
...
</application>
</manifest>
Does this work?
public String CalculateSum()
{
Random generator=new Random();
int n=generator.nextInt();
int m=generator.nextInt();
String sum = Integer.toString(n+m) ;
Log.v("CalculateSum", "N+M = " + sum);
return sum;
}