My app to access a simple JSON and display it runs perfectly fine on the emulator(PIXEL 2 API 24) but not on any actual device I connect to it. Tried with both S8 and Note10, neither have data saver on either.
I even checked the apps data use afterwards and it said "0 B".
Here are the files:
MainActivity.java:
package com.example.internettest;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
Button button;
TextView textView;
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
textView = (TextView) findViewById(R.id.textView);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JsonTask().execute("http://46d30cf268b0.ngrok.io/LEATest/");
}
});
}
private class JsonTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
//pd = new ProgressDialog(MainActivity.this);
//pd.setMessage("Please wait");
//pd.setCancelable(false);
//pd.show();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line+"\n");
Log.d("Response: ", "> " + line); //here u ll get whole response...... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//if (pd.isShowing()){
// pd.dismiss();
//}
Toast toast = Toast.makeText(getApplicationContext(),
"Before Try = |" + result + "|",
Toast.LENGTH_SHORT);
toast.show();
textView.setText(result);
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.internettest">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
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>
</activity>
</application>
</manifest>
Here's the result of pressing the button on the emulator(all fake username/passwords):
Execure your JsonTask as follows -
new JsonTask().execute("https://46d30cf268b0.ngrok.io/LEATest/");
As suggested by #isthemartin, when you are running you app in actual device (S8 and Note10) the traffic is getting block because HTTP connection is not allowed.
Either you can add android:usesCleartextTraffic="true" but then you app will allow non secure HTTP connections.
I tried your API URL (https://46d30cf268b0.ngrok.io/LEATest/) is responding to the request so, why don't simply use it without making a security gap in your app.
probably your actual devices are blocking http connections, so in this case you need to enable those connections, check this post
Please add this code to your AndroidManifest.xml file.
android:usesCleartextTraffic="true"
so the code can be like this :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.internettest">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:usesCleartextTraffic="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>
</activity>
</application>
Related
I was creating an application to test whether File.listFiles() method is working or not. To check this I made an application and I used it there but this returning null in place of an array. This is my full code please help and I have granted all permissions for android 11
Manifest File
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.myapplication">
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE"
tools:node="merge" />
<uses-permission
android:name="android.permission.STORAGE"
tools:node="merge" />
<uses-permission
android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
tools:ignore="ScopedStorage" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:requestLegacyExternalStorage="true"
android:theme="#style/Theme.MyApplication">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity.java
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
public class MainActivity extends AppCompatActivity {
private Button deleteButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
deleteButton = findViewById(R.id.deleteButton);
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
deleteFiles(view);
}
});
}
private void deleteFiles(View v) {
File file = new File("/storage/emulated/0/DCIM/");
if (file.isDirectory())
{
File[] files;
files = file.listFiles();
int a = files.length;
for (int i = 0; i < files.length; i++)
{
new File(file, files[i].getName()).delete();
}
Toast.makeText(getApplicationContext(), "Done", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(getApplicationContext(), (CharSequence) file, Toast.LENGTH_LONG).show();
}
}
}
I am trying to start up an android app as background service after initial run. At first run, the app should start as normal android app, then after, that it should be a background service which still runs even after booting. I wrote the following code. The service class is verified as standalone android app. But this app is not running as expected. No error code, but when debug, service class is not working.
Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tulga.nar.mytrack">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main"
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>
Initial one time running activity class:
package com.tulga.nar.mytrack;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
}
public void starterHandler(View v)
{
new MyBroadcastReceiver();
}
}
Initial one time running activity class's xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.tulga.nar.mytrack.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/starter"
android:text="start service"
android:onClick="starterHandler"/>
</android.support.constraint.ConstraintLayout>
Broadcast receiver class. It is called from MainActivity after start service button is clicked. It is supposed to start background MyService class.
package com.tulga.nar.mytrack;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context aContext, Intent aIntent) {
// This is where you start your service
aContext.startService(new Intent(aContext, MyService.class));
}
}
This is background MyService class. The class is verified and works as standalone app. But here, code execution is not reaching to here when debug.
package com.tulga.nar.mytrack;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by Home on 8/27/2017.
*/
public class MyService extends AppCompatActivity implements
LocationListener
{
private class SendDeviceDetails extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String data = "";
HttpURLConnection connection = null;
try {
URL url=new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-Type",
"application/json");
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.connect();
DataOutputStream wr = new
DataOutputStream(connection.getOutputStream());
wr.writeBytes(params[1]);
wr.flush();
wr.close();
InputStream in = connection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(in);
int inputStreamData = inputStreamReader.read();
while (inputStreamData != -1) {
char current = (char) inputStreamData;
inputStreamData = inputStreamReader.read();
data += current;
}
} //catch (Exception e) {
//e.printStackTrace();
//}
catch (MalformedURLException e) {
e.printStackTrace();}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (connection != null) {
connection.disconnect();
}
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.e("TAG", result); // this is expecting a response code to be
sent from your server upon receiving the POST data
}
}
public static final int RequestPermissionCode = 1 ;
static public double myLong=151;
static public double myLat=-34;
static public String _id=null;
static public String _rev=null;
Button buttonEnable, buttonGet ;
TextView textViewLongitude, textViewLatitude ;
Context context;
Intent intent1 ;
Location location;
LocationManager locationManager ;
boolean GpsStatus = false ;
Criteria criteria ;
String Holder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
EnableRuntimePermission();
locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
criteria = new Criteria();
Holder = locationManager.getBestProvider(criteria, false);
context = getApplicationContext();
CheckGpsStatus();
JSONObject postData = new JSONObject();
try {
postData.put("_id",String.valueOf("9876543210"));
postData.put("Lat",
String.valueOf(String.valueOf(MyService.myLat)));
postData.put("Long",
String.valueOf(String.valueOf(MyService.myLong)));
postData.put("_rev",String.valueOf("1-
62076042d87cacd2711268d4a396129b"));
new SendDeviceDetails().execute("my-server-name/mydatabase",
postData.toString());
}
catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onLocationChanged(Location location) {
textViewLongitude.setText("Longitude:" + location.getLongitude());
textViewLatitude.setText("Latitude:" + location.getLatitude());
myLong=location.getLongitude();
myLat=location.getLatitude();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
public void CheckGpsStatus(){
locationManager =
(LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
GpsStatus =
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
public void EnableRuntimePermission(){
if (ActivityCompat.shouldShowRequestPermissionRationale(MyService.this,
Manifest.permission.ACCESS_FINE_LOCATION))
{
Toast.makeText(MyService.this,"ACCESS_FINE_LOCATION permission
allows us to Access GPS in app", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(MyService.this,new String[]{
Manifest.permission.ACCESS_FINE_LOCATION},
RequestPermissionCode);
}
}
#Override
public void onRequestPermissionsResult(int RC, String per[], int[] PResult)
{
switch (RC) {
case RequestPermissionCode:
if (PResult.length > 0 && PResult[0] ==
PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MyService.this,"Permission Granted, Now your
application can access GPS.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MyService.this,"Permission Canceled, Now your
application cannot access GPS.", Toast.LENGTH_LONG).show();
}
break;
}
}
You didn't regest your serice in mainifest,and your broadcastReceiver is not at the right place.It should like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tulga.nar.mytrack">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application android:allowBackup="true" android:icon="#mipmap/ic_launcher"
android:label="#string/app_name" android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true" android:theme="#style/AppTheme">
<activity android:name=".MainActivity" android:label="#string/title_activity_main"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:name=".service.MyService">
<intent-filter>
<action android:name="write your action name" />
</intent-filter>
</service>
</application>
</manifest>
I wrote that code to send data to parse.com then to receive it also but I can't even send it till now, why ?!! I don't know the main reason, I put the internet and network permission in AndroidManifest.xml the parse class in application also in AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mkadaimtwo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:name="com.example.mkadaimtwo.ParseCode"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".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>
and also put the parse class in application also in AndroidManifest.xml and that two codes of class and main Activity
ParseCode class Activity :
package com.example.mkadaimtwo;
import com.parse.Parse;
import android.app.Application;
public class ParseCode extends Application {
public void onCreate() {
Parse.initialize(this, "GIuhlGILKRd8itvCF79femTyReHM6XjVkrfLKm3X", "Fjg4tBrMgl0mY47K4kCL7hVmXhu8FmkE2on9PlXK");
}
}
the MainActivity Code :
package com.example.mkadaimtwo;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.net.ParseException;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.EditText;
import com.parse.GetCallback;
import com.parse.ParseObject;
import com.parse.ParseQuery;
public class MainActivity extends ActionBarActivity {
EditText etCompanyName,etAddress,etNumberOfEmployees,etContactNumber;
ProgressDialog pd,pd2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etCompanyName = (EditText) findViewById(R.id.etCompanyName);
etAddress = (EditText) findViewById(R.id.etAddress);
etNumberOfEmployees = (EditText) findViewById(R.id.etNumberOfEmployees);
etContactNumber = (EditText) findViewById(R.id.etContactNumber);
pd = new ProgressDialog(this);
pd.setTitle("wait");
pd.setMessage("by7aml elmafrod");
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.setCancelable(true);
pd2 = new ProgressDialog(this);
pd2.setTitle("wait");
pd2.setMessage("by7aml elmafrod");
pd2.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd2.setCancelable(true);
//here we will Load the old company data from Parse.com
ParseQuery<ParseObject> query = ParseQuery.getQuery("TestBosyApp");
query.getInBackground("ijy1qi78g8", new GetCallback<ParseObject>() {
public void done(ParseObject testBosyApp, ParseException e) {
if (e == null) {
String companyName = testBosyApp.getString("company_name");
String address = testBosyApp.getString("address");
String numberOfEmployees = testBosyApp.getString("number_of_employees");
String contactNumber = testBosyApp.getString("contact_number");
etCompanyName.setText(companyName);
etAddress.setText(address);
etNumberOfEmployees.setText(numberOfEmployees);
etContactNumber.setText(contactNumber);
pd.dismiss();
} else {
AlertDialog.Builder mDialoge = new AlertDialog.Builder(MainActivity.this);
mDialoge.setTitle("Erorr");
mDialoge.setMessage("Check el net plz :)");
mDialoge.setPositiveButton("ok", null);
mDialoge.show();
}
}
#Override
public void done(ParseObject arg0, com.parse.ParseException arg1) {
// TODO Auto-generated method stub
}
});
}
public void update (View V){
pd2.show();
//update data in Parse
ParseQuery<ParseObject> myQuery = ParseQuery.getQuery("TestBosyApp");
// Retrieve the object by id
myQuery.getInBackground("U6Gwn2tiD8", new GetCallback<ParseObject>() {
public void done(ParseObject testBosyApp, ParseException e) {
if (e == null) {
//Initials our variables
String companyName = etCompanyName.getText().toString().trim();
String address = etAddress.getText().toString().trim();
String numberOfEmployees = etNumberOfEmployees.getText().toString().trim();
String contactNumber = etContactNumber.getText().toString().trim();
//update it with new data
testBosyApp.put("company_name", companyName);
testBosyApp.put("address", address);
testBosyApp.put("number_of_employees", numberOfEmployees);
testBosyApp.put("contact_number", contactNumber);
testBosyApp.saveInBackground();
pd2.dismiss();
AlertDialog.Builder mDialoge = new AlertDialog.Builder(MainActivity.this);
mDialoge.setTitle("2shta");
mDialoge.setMessage("Keda eldata ra7t t2riban");
mDialoge.setPositiveButton("cool", null);
mDialoge.show();
}else{
pd2.dismiss();
AlertDialog.Builder mDialoge = new AlertDialog.Builder(MainActivity.this);
mDialoge.setTitle("Erorr");
mDialoge.setMessage("Check el net plz :)");
mDialoge.setPositiveButton("ok", null);
mDialoge.show();
}
}
#Override
public void done(ParseObject arg0, com.parse.ParseException arg1) {
// TODO Auto-generated method stub
}
});
}
}
so what's the problem, progress-bar is loading without end and if I give progress-bar cancellation feature then put data in fields there's nothing happen .
plus if anyone have tutorials for use android with parse.com please provide me with it.
Dude.. Sir? goto parse.com, there are tutorials.. you need to enable something i just do not remember Go to settings ->App Permissions ->Allow client class creation. Set it to ON> before you can send push from device and receive it.. also your manifest is not complete.. from what i know..
<application
android:name="com.example.mkadaimtwo.ParseCode"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".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>
//edit started here
<service android:name="com.parse.PushService" />
<receiver android:name="com.parse.ParseBroadcastReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.USER_PRESENT" />
</intent-filter>
</receiver>
</application>
so copy and paste this manifest
I am trying to create very basic network application, which will connect to google through socket, and send "GET" and print the output in a text view. but it appears that socket never connects... what am I doing wrong ??
here is the code
MainActiviy:
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import java.io.*;
import java.net.*;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tva = (TextView) this.findViewById(R.id.tv);
String str = "";
try {
Socket sock = new Socket("www.google.com", 80);
str = sock.getRemoteSocketAddress().toString();
tva.setText("Connected to: " + str);
DataOutputStream out = new DataOutputStream(sock.getOutputStream());
out.writeUTF("GET //");
BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
str = br.readLine();
while(str != null) {
tva.setText(str);
str = br.readLine();
}
out.close();
br.close();
sock.close();
} catch(Exception ex) {
}
}
}
manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.onik.netw"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.onik.netw.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>
you are trying to use sockets on main UI thread, you will get exception android.os.NetworkOnMainThreadException
Move the try {} block into a separate thread. Since this will run on non-UI thread you cant access UI elements, so you need to pass the data back to main thread may be via Handler, so it can display the data received.
For a quick test, enclose that entire try block inside an anonymous thread
new Thread() {
public void run() {
// your try block goes here
}
}.start();
replace tva.setText with Log.d("test", str)
Simple Concept that is not working:
I'm trying to connect to the web and retrieve some data with an asynchronous connection. When the connection returns data, I want to switch to another activity. My code ain't workin'.
I'm assuming that I'll need to use a callback of some sort but I'm new to Android / Java and have not been able to find out how to do it by Googling. Can someone please have a look and suggest how I can create a callback that starts the intent when the data returns?:
*UPDATE: I found this nice library here http://loopj.com/android-async-http/ which is an alternative (easy) way to connect to the web in the background.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mtmobtest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:icon="#drawable/icon"
android:label="#string/app_name" >
<activity
android:label="#string/app_name"
android:name=".MTMobTestActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:label="MainMenu"
android:name=".MainMenu" >
<intent-filter >
<action android:name="android.intent.action.MAINMENU" />
<category android:name="android.intent.category.MAINMENU" />
</intent-filter>
</activity>
</application>
</manifest>
MTMobTestActivity.java
package com.mtmobtest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Window;
import android.widget.Toast;
import android.widget.ViewFlipper;
public class MTMobTestActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
postData("Sup yall");
setContentView(R.layout.main);
}
public void postData(String toPost) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.example.com/test.php");
//This is the data to send
String myName = "anybody there?"; //any data to send
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("action", myName));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httppost, responseHandler);
//This is the response from a php application
String reverseString = response;
//ViewFlipper vf = (ViewFlipper) findViewById(R.layout.menu);
// Set an animation from res/anim: I pick push left in
//vf.setAnimation(AnimationUtils.loadAnimation(view.getContext(), R.anim.push_left_in));
//vf.showNext();
Toast.makeText(this, "response" + reverseString, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
Toast.makeText(this, "CPE response " + e.toString(), Toast.LENGTH_LONG).show();
// TODO Auto-generated catch block
} catch (IOException e) {
Toast.makeText(this, "IOE response " + e.toString(), Toast.LENGTH_LONG).show();
// TODO Auto-generated catch block
}
Intent intent = new Intent(this, MainMenu.class);
startActivity(intent);
}
}
Use an AsyncTask for the job and fire the new Activity in the AsyncTasks onPostExecute method call.