Android - HTTP Post request [duplicate] - java

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 5 years ago.
I want to call a POST request, to send some geo information from my android device to my server.
My server use PHP and I want use a php script to save all incoming post requests in my database. My php script works fine when I tried it with curl, but when I want to send some information from my android device I get some network errors.
Here is my error log
12-11 12:08:02.871 10241-10241/local.example.markus.geoapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: local.example.markus.geoapp, PID: 10241
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1448)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:102)
at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:90)
at java.net.InetAddress.getAllByName(InetAddress.java:787)
at com.android.okhttp.Dns$1.lookup(Dns.java:39)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:175)
at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:141)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:83)
at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:174)
at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:127)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:258)
at com.android.tools.profiler.support.network.httpurl.TrackedHttpURLConnection.getOutputStream(TrackedHttpURLConnection.java:288)
at com.android.tools.profiler.support.network.httpurl.HttpURLConnection$.getOutputStream(HttpURLConnection$.java:212)
at local.example.markus.geoapp.MapsListener.sendPost(MapsListener.java:121)
at local.example.markus.geoapp.MapsListener.onLocationChanged(MapsListener.java:77)
at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:291)
at android.location.LocationManager$ListenerTransport.-wrap0(Unknown Source:0)
at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:236)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Here is my java code
package local.example.markus.geoapp;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Timestamp;
/**
* Created by markus on 04.12.17.
*/
public class MapsListener implements LocationListener {
// Member Variablen
private GoogleMap googleMap;
// Konstruktor
public MapsListener() {
}
// Getter und Setter
public GoogleMap getGoogleMap() {
return googleMap;
}
public void setGoogleMap(GoogleMap googleMap) {
this.googleMap = googleMap;
}
// Interface Methods
#Override
public void onLocationChanged(Location location) {
// Print new Latitide and Logtitude into log
Log.d("INFO", "New Location! Latitude: '" + location.getLatitude() + "', '" + location.getLongitude() + "'");
// Define new Latitude and Logtitude object
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
// Add a new Marker to the Map
this.googleMap.addMarker(new MarkerOptions().position(latLng).title("Lat:" + location.getLatitude() + ", Lng: " + location.getLongitude()));
// Build ca,era position
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location.getLongitude())) // Sets the center of the map to location user
.zoom(17) // Sets the zoom
.bearing(0) // Sets the orientation of the camera to north
.tilt(40) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
// Animate camera to zoom to the new position with defined settings
this.googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
Log.d("Device ID", this.getDeviceId());
this.sendPost(location);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
private String getDeviceId() {
if (Build.VERSION.SDK_INT <= 25) {
return Build.SERIAL;
} else {
return Build.getSerial();
}
}
private void sendPost(Location location) {
URL url = null;
HttpURLConnection httpURLConnection = null;
OutputStream outputStream = null;
try{
url = new URL("http://example.local");
httpURLConnection = (HttpURLConnection) url.openConnection();
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
/*httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("d", this.getDeviceId());
httpURLConnection.setRequestProperty("lat", Double.toString(location.getLatitude()));
httpURLConnection.setRequestProperty("lon", Double.toString(location.getLongitude()));
httpURLConnection.setRequestProperty("t", timestamp.toString());
httpURLConnection.setDoOutput(true);*/
outputStream = new BufferedOutputStream(httpURLConnection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(Double.toString(location.getLongitude()));
writer.flush();
writer.close();
outputStream.close();
httpURLConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
How I can send some information about POST requests to my php script on http://example.local/gps.php?
The post Sending POST data in Android does not work.

The post Sending POST data in Android does not work.
The above should work absolutely fine else ans would have been not in accepted and upvoted state.
The error what you're getting obvious since missed how the network call is made in that ans
You missed below one.
public class CallAPI extends AsyncTask {
In android or other platforms most of the platforms also network call ui thread is not allowed. In Android AsyncTask is one way making network call off the ui thread.

This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in AsyncTask.
public class HttpPost extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
URL url = null;
HttpURLConnection httpURLConnection = null;
OutputStream outputStream = null;
try{
url = new URL("http://example.local");
httpURLConnection = (HttpURLConnection) url.openConnection();
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
/*httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("d", this.getDeviceId());
httpURLConnection.setRequestProperty("lat", Double.toString(location.getLatitude()));
httpURLConnection.setRequestProperty("lon", Double.toString(location.getLongitude()));
httpURLConnection.setRequestProperty("t", timestamp.toString());
httpURLConnection.setDoOutput(true);*/
outputStream = new BufferedOutputStream(httpURLConnection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(Double.toString(location.getLongitude()));
writer.flush();
writer.close();
outputStream.close();
httpURLConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
protected void onPostExecute(String result) {
//What you want to do with the result
//Call a callback function for instance
//You can also delete this method if you dont expect a result
}
}

Related

My application crashes after a button click

I am very new to android development with a small amount of Java programming knowledge. I need help! I am making an app that allows you to enter the amount of money you spend and it calculates how much more you can spend. It also keeps track of the budget that you have left inside of a text file. It is made in android studio using Java.
Here is my error message:
2019-03-03 09:42:14.245 4178-4178/? E/SPPClientService: [PackageInfoChangeReceiver] [handlePkgRemovedEvent] PackageName : com.concretegames.budgettracker, true, false
2019-03-03 09:42:27.573 16961-16961/com.concretegames.budgettracker E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.concretegames.budgettracker, PID: 16961
java.lang.NumberFormatException: s == null
at java.lang.Integer.parseInt(Integer.java:570)
at java.lang.Integer.parseInt(Integer.java:643)
at com.concretegames.budgettracker.MainActivity$1.onClick(MainActivity.java:56)
at android.view.View.performClick(View.java:6935)
at android.widget.TextView.performClick(TextView.java:12738)
at android.view.View$PerformClick.run(View.java:26211)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:7000)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:441)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
And here is my code:
package com.concretegames.budgettracker;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import static java.lang.System.out;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView response = findViewById(R.id.response);
final Button calc = findViewById(R.id.Calculate);
Context context = this;
String filepath = "total_expense.txt";
String filestoragepath = "MyFileStorage";
final File edit_file = new File(getExternalFilesDir(filestoragepath), filepath);
EditText $box = findViewById(R.id.expenses);
final String $ = $box.getText().toString();
calc.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (edit_file.exists() && !edit_file.isDirectory()) {
try {
FileReader fr = new FileReader(edit_file);
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
out.println(str + "\n");
}
br.close();
int result = Integer.parseInt(str) - Integer.parseInt($);
FileWriter fw = new FileWriter(edit_file);
PrintWriter pw = new PrintWriter(fw);
pw.print("");
pw.print(result);
pw.close();
response.setText("Budget left over: "+result);
} catch (IOException e) {
out.println("ERROR: " + e.toString());
response.setText("ERROR: " + e.toString());
}
} else {
try {
edit_file.createNewFile();
FileWriter fw = new FileWriter(edit_file);
PrintWriter pw = new PrintWriter(fw);
pw.print("1500");
pw.close();
} catch (IOException e) {
out.println("ERROR: " + e.toString());
response.setText("ERROR: " + e.toString());
}
}
}
});
}
}
P.S. I'm only 13 and don't have experience with Java. I prefer HTML, python, and javascript. Any help is appreciated!
Integer.parseInt() throws an exception if it can't successfully parse the String into an int. But the exception that is thrown is a subclass of RuntimeException, so the java compiler does not force you to catch the exception. But it's still highly suggested that you do catch it. And the crash will be avoided. In general, do something like this when parsing Strings into ints:
int result;
try {
result = Integer.parseInt(someString);
} catch (NumberFormatException e) {
result = 0;
}
Problem is in the following line:
int result = Integer.parseInt(str) - Integer.parseInt($);
NumberFormatException is an Exception that might be thrown when you try to convert a String into a number. Here one of the strings is null (I think str is null).
When string is null, Integer.parseInt(null) would not be able to get integer value from null string. If string contains proper value, this exception will not come.
Hence to avoid this exception either apply null check before fetching value of integer from string or keep it in try catch (NumberFormatException e)

Running HTTP Request in seperate Thread not working

I have been trying to get some very simple code to work which should read an online file and print the contents of that file in the log. At first I didn't know that it needed to be handled in a seperate thread so I left it in the onCreate Method. Now I put it into a seperate Thread with the help of this question: How to use separate thread to perform http requests but the app still crashes! Since I'm desperate to get this working so I can keep on learning how to program this app, I will insert the exact code I used:
package com.dan6erbond.schoolhelper;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private String link = "https://dan6erbond.github.io/I1A/Documents/Zusammenfassungen/Zusammenfassungen.json";
String content;
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
Log.i("TAG", content);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread downloadFile = new Thread(new Runnable(){
#Override
public void run(){
try {
URL url = new URL(link);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
String str;
while ((str = in.readLine()) != null) {
content += str;
}
Log.i("TAG", content);
in.close();
} catch (Exception e) {
Log.i("TAG", "Error occured!");
}
handler.sendEmptyMessage(0);
}
});
downloadFile.start();
}
}
In the log the error message is being sent:
01-05 07:40:33.320 9601-9622/com.dan6erbond.schoolhelper I/TAG: Error occured!
I'd be really happy if someone could help me with this problem. It's probably very simple but I just started coding in Android Studio so I'm really new to this.
I just needed to add the INTERNET permission. I figured that out by printing the error message:
Log.i("TAG", e.getMessage());
Which resulted in this:
01-05 08:05:10.806 11815-11838/com.dan6erbond.schoolhelper I/TAG: Permission denied (missing INTERNET permission?)
I just added this to the Android Manifest:
<uses-permission android:name="android.permission.INTERNET"/>
Thanks everyone for your help!

Connect Bluetooth Android Client to Bluetooth Java Server

I've been following these two posts SPP Server and Client and this stackoverflow post. I have the server running on a Linux VM and the Android app running on a Samsung Galaxy S6. When I run the server code in Intellij, it says:
"Server Started. Waiting for clients to connect".
When I run the Android app, I get the following Alert box saying:
"Fatal Error. In OnResume()and an exception occurred during write: socket closed.
Check that the SPP UUID: 00001101-0000-1000-8000-00805F9B34FB exists on server. Press OK to exit.
Why is this happening and how can I resolve it so the server will connect and receive a string from the Android app?
SPP Server Code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import javax.bluetooth.*;
import javax.microedition.io.*;
public class SampleSPPServer {
//start server
private void startServer() throws IOException{
//Create a UUID for SPP
UUID uuid = new UUID("0000110100001000800000805F9B34FB", false);
//Create the servicve url
String connectionString = “btspp://localhost:” + uuid +”;name=Sample
SPP Server”;
//open server url
StreamConnectionNotifier streamConnNotifier =
(StreamConnectionNotifier)Connector.open( connectionString );
//Wait for client connection
System.out.println(“\nServer Started. Waiting for clients to connect…”);
StreamConnection connection=streamConnNotifier.acceptAndOpen();
RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
System.out.println(“Remote device address: “+dev.getBluetoothAddress());
System.out.println(“Remote device name: “+dev.getFriendlyName(true));
//read string from spp client
InputStream inStream=connection.openInputStream();
BufferedReader bReader=new BufferedReader(new
InputStreamReader(inStream));
String lineRead=bReader.readLine();
System.out.println(lineRead);
//send response to spp client
OutputStream outStream=connection.openOutputStream();
PrintWriter pWriter=new PrintWriter(new OutputStreamWriter(outStream));
pWriter.write(“Response String from SPP Server\r\n”);
pWriter.flush();
pWriter.close();
streamConnNotifier.close();
}
public static void main(String[] args) throws IOException {
//display local device address and name
LocalDevice localDevice = LocalDevice.getLocalDevice();
System.out.println(“Address: “+localDevice.getBluetoothAddress());
System.out.println(“Name: “+localDevice.getFriendlyName());
SampleSPPServer sampleSPPServer=new SampleSPPServer();
sampleSPPServer.startServer();
}
}
Android Client Code:
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.UUID;
public class BluetoothClient extends AppCompatActivity {
TextView out;
private static final int REQUEST_ENABLE_BT = 1;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
// Well known SPP UUID
private static final UUID MY_UUID =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// Insert your server's MAC address
private static String address = "00:10:60:AA:B9:B2";
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth_client);
out = (TextView) findViewById(R.id.out);
out.append("\n...In onCreate()...");
btAdapter = BluetoothAdapter.getDefaultAdapter();
CheckBTState();
}
public void onStart() {
super.onStart();
out.append("\n...In onStart()...");
}
public void onResume() {
super.onResume();
out.append("\n...In onResume...\n...Attempting client connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
AlertBox("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
try {
btSocket.connect();
out.append("\n...Connection established and data link opened...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
AlertBox("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
out.append("\n...Sending message to server...");
String message = "Hello from Android.\n";
out.append("\n\n...The message that we will send to the server is: "+message);
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
AlertBox("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
}
byte[] msgBuffer = message.getBytes();
try {
outStream.write(msgBuffer);
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 37 in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";
AlertBox("Fatal Error", msg);
}
}
public void onPause() {
super.onPause();
//out.append("\n...Hello\n");
InputStream inStream;
try {
inStream = btSocket.getInputStream();
BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream));
String lineRead=bReader.readLine();
out.append("\n..."+lineRead+"\n");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.append("\n...In onPause()...");
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
AlertBox("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
}
}
try {
btSocket.close();
} catch (IOException e2) {
AlertBox("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
public void onStop() {
super.onStop();
out.append("\n...In onStop()...");
}
public void onDestroy() {
super.onDestroy();
out.append("\n...In onDestroy()...");
}
private void CheckBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null) {
AlertBox("Fatal Error", "Bluetooth Not supported. Aborting.");
} else {
if (btAdapter.isEnabled()) {
out.append("\n...Bluetooth is enabled...");
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
}
public void AlertBox( String title, String message ){
new AlertDialog.Builder(this)
.setTitle( title )
.setMessage( message + " Press OK to exit." )
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
finish();
}
}).show();
}
}
Android Studio Logcat:
android.view.WindowLeaked: Activity com.example.toby.btclientapp.BluetoothClient has leaked window com.android.internal.policy.PhoneWindow$DecorView{b73d40d V.E...... R.....I. 0,0-1368,1249} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:569)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:326)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.app.Dialog.show(Dialog.java:350)
at android.support.v7.app.AlertDialog$Builder.show(AlertDialog.java:955)
at com.example.toby.btclientapp.BluetoothClient.AlertBox(BluetoothClient.java:181)
at com.example.toby.btclientapp.BluetoothClient.onResume(BluetoothClient.java:107)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1286)
at android.app.Activity.performResume(Activity.java:6987)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4145)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4250)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3361)
at android.app.ActivityThread.access$1100(ActivityThread.java:222)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1795)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
07-26 13:09:21.574 3857-3857/? E/WindowManager: android.view.WindowLeaked: Activity com.example.toby.btclientapp.BluetoothClient has leaked window com.android.internal.policy.PhoneWindow$DecorView{9723488 V.E...... R....... 0,0-1368,1249} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:569)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:326)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.app.Dialog.show(Dialog.java:350)
at android.support.v7.app.AlertDialog$Builder.show(AlertDialog.java:955)
at com.example.toby.btclientapp.BluetoothClient.AlertBox(BluetoothClient.java:181)
at com.example.toby.btclientapp.BluetoothClient.onResume(BluetoothClient.java:107)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1286)
at android.app.Activity.performResume(Activity.java:6987)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4145)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4250)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1839)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
07-26 13:09:21.574 3857-3857/? E/WindowManager: android.view.WindowLeaked: Activity com.example.toby.btclientapp.BluetoothClient has leaked window com.android.internal.policy.PhoneWindow$DecorView{cea821b V.E...... R....... 0,0-1368,799} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:569)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:326)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.app.Dialog.show(Dialog.java:350)
at android.support.v7.app.AlertDialog$Builder.show(AlertDialog.java:955)
at com.example.toby.btclientapp.BluetoothClient.AlertBox(BluetoothClient.java:181)
at com.example.toby.btclientapp.BluetoothClient.onPause(BluetoothClient.java:135)
at android.app.Activity.performPause(Activity.java:7033)
at android.app.Instrumentation.callActivityOnPause(Instrumentation.java:1339)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:4577)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:4550)
at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:4525)
at android.app.ActivityThread.access$1300(ActivityThread.java:222)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1813)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
I needed to change the MAC address of the Bluetooth adapter. It works now.

Apk File download Error using Java in Android

.I followed this tutorial and getting errors "PARSING ERROR THERE IS A PROBLEM PARSING THE PACKAGE". I have check the result in Android Device Samsung Galaxy S3.
package com.mrfs.android.surveyapp.activities;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
public class ApkFileAsync extends Activity
{
UpdateApp updateAppInstance;
#Override
public void onCreate(Bundle savedBundleInstance)
{
super.onCreate(savedBundleInstance);
updateAppInstance = new UpdateApp();
updateAppInstance.setContext(getApplicationContext());
updateAppInstance.execute("http://demo.ingresssolutions.com/proposalmanagement/services/user/getApkFile");
}
private class UpdateApp extends AsyncTask<String,Void,Void>{
private Context context;
public void setContext(Context contextf){
context = contextf;
}
#Override
protected Void doInBackground(String... arg0) {
try {
URL url = new URL(arg0[0]);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("POST");
c.setDoOutput(true);
c.connect();
String PATH = "/mnt/sdcard/Download/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file,"surveyapp.apk");
if(outputFile.exists()){
outputFile.delete();
}
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
/* Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File("/mnt/sdcard/Download/update.apk")), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);*/ // without this flag android returned a intent error!
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" + "app.apk")), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
context.startActivity(intent);
} catch (Exception e) {
Log.e("UpdateAPP", "Update error! " + e.getMessage());
}
return null;
}}
}
I am getting this error after Complete Action using dialog when trying to press either PACKAGE INSTALLER or VERIFY AND INSTALL in both cases same error.
Change your manifes to like
This should work fine i think.. If not worked please post your tutorial link i missed it.. i need to check it.. and i will update answer...
and also mention how you are installing app wether by eclipse or by some other process like importing apk... IF importing apk to real device means please check ur device version, If its s3 mans it has ICS api level includes 14 or 15 so change that.. if its jellly bean means you can use up to 18

how to generate a identified filename from url?

Now I have to download a file whose url has known. I need to save it to SD card when download action finished. The problem is I should know whether the file is existed before downloading. So I plan to save the file with a identified filename which is generated from url. So when I get the url I can calculate his corresponding filename. Which algorithm should I use?
BTW, JAVA is what I'm using.
Maybe, I have not told my requirement clearly. Fetch the filename "abc.png" from url "www.yahoo.com/abc.png" is not what I need. Because "www.google.com/abc.png" results the same filename. I need to generate a unique filename from url.
full example working ...i tried myself some days ago..
im sure it will help..
package com.imagedownloader;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
public class ImageDownloaderActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Bitmap bitmap=DownloadImage("http://www.allindiaflorist.com/imgs/arrangemen4.jpg");
ImageView img =(ImageView)findViewById(R.id.imageView1);
img.setImageBitmap(bitmap);
}
private Bitmap DownloadImage(String URL) {
// TODO Auto-generated method stub
Bitmap bitmap=null;
InputStream in=null;
try {
in=OpenHttpConnection(URL);
bitmap=BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bitmap;
}
private InputStream OpenHttpConnection(String stingurl) throws IOException {
// TODO Auto-generated method stub
InputStream in=null;
int response=-1;
URL url = new URL(stingurl);
URLConnection conn=url.openConnection();
if(!(conn instanceof HttpURLConnection))
throw new IOException("not and http exception");
try{
HttpURLConnection httpconn=(HttpURLConnection)conn;
httpconn.setAllowUserInteraction(false);
httpconn.setInstanceFollowRedirects(true);
httpconn.setRequestMethod("GET");
httpconn.connect();
response=httpconn.getResponseCode();
if(response==HttpURLConnection.HTTP_OK)
{
in=httpconn.getInputStream();
}
}
catch(Exception ex)
{throw new IOException("Error connecting"); }
return in;
}
}

Categories