Snippet provided:
public void update(){
try {
Socket appSoc = new Socket( "XXX.XXX.XXX.X" ,XXXXX);
BufferedReader in = new BufferedReader(new
InputStreamReader(appSoc.getInputStream()));
for (int i = 0; i < 100; i++) {
String message = in.readLine();
add(message);}
}
catch (Exception e) {
add("ERROR" + e);
}
}
add(String text) adds text to a textview.
Using the domain name instead of the IP address says that the phone cannot find the domain, is this an android problem, because it runs fine on java on the desktop.
You are probably missing the Internet persmission in your manifest. Make sure it is located outside of the application tag, like this:
<manifest>
<application>
.
.
.
</application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
In your androidmanifest.xml, check to see if you have given proper internet permissions.
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Related
I am trying to connect a simple android client to a simple java server on another computer running on the same wi-fi network, i was able to connect with a java code(non android) on eclipse, and the server works just fine, but when i take the same code and put in my android app (android studio), it throws an IOException.
As of right now my protocol just returns a string "yay" and i just want to display it in a View.
My code:
private void createCom2(TextView showResult){
Socket pazeSocket = null;
PrintWriter pw = null;
BufferedReader br = null;
String ip = "10.0.0.4";
try {
pazeSocket = new Socket(ip, 4444);
pw = new PrintWriter(pazeSocket.getOutputStream());
br = new BufferedReader(new InputStreamReader(pazeSocket.getInputStream()));
} catch (UnknownHostException e) {
Toast.makeText(this,"Don't know about host: " + ip , Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(this,"Couldn't get I/O for the connection to: " + ip , Toast.LENGTH_SHORT).show();
}
}
Thanks.
You need Internet permission for your app. Add this line to your manifest file:
<uses-permission android:name="android.permission.INTERNET"/>
and read more abut permissions here, if you like:
http://developer.android.com/guide/topics/manifest/manifest-intro.html
I have some trouble with the ObjectInputStream in an little android project. On my Laptop I have a Server running, which respondes an int to a String, which comes from my client (running on my andoid device).
Here is my Server:
ServerSocket socketmaker = new ServerSocket(30001);
Socket tSocket = socketmaker.accept();
ObjectInputStream in = new ObjectInputStream(tSocket.getInputStream());
ObjectOutputStream out = new ObjectOutputStream(tSocket.getOutputStream());
String text = "";
int hashed = 0;
text = (String) in.readObject();
System.out.print("The Client asks with \""+text+"\"");
hashed = hash(text);
out.writeUTF(String.valueOf(hashed));
System.out.print(" and we answer with the hash \""+hashed+"\"\n");
out.close();
in.close();
tSocket.close();
And here comes the app:
public void onClick(View v) {
String server = host.getText().toString();
int portNr = Integer.parseInt(port.getText().toString());
try {
Socket tSocket = new Socket(server, portNr);
ObjectOutputStream out = new ObjectOutputStream(tSocket.getOutputStream());
ObjectInputStream in = new ObjectInputStream(tSocket.getInputStream());
String text = content.getText().toString();
out.writeObject(text);
int re = Integer.parseInt(in.readUTF());
Toast.makeText(ClientActivity.this, re, Toast.LENGTH_SHORT).show();
out.close();
in.close();
tSocket.close();
} catch(Exception e) {
//print ex here...
}
}
host, port, conent are EditText's and allow the client to put in the serverinfo.
I run the server on a console and it receives the text from the client and prints out:
The Client asks with "test" and we answer with the hash "48"
But then the app closes with an error.
So the error has to be with the server sending the int and the app receiving it.But I also set the permissions in the Manifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
I also tried it with:
writeObject(int) - Integer.parseInt(readObject())
writeObject(String) - readObject()
writeInt(int) - readInt()
but none of them worked.
So please help me, and excuse my bad english (non native).
Thanks
I want to read file from external storage. I uploaded the file in Eclipse DDMS to storage/sdcard (image below). But whenever I tried to read, I got an error of permission denied. Is there any problem in my file permission? Or I need to add anything in manifest file (I am not writing anything at the moment)?
Any help will be appreciated.
Code:
public void extimport(View v){
EditText xedittxt = (EditText) findViewById(R.id.frmexttxt);
String xedit = xedittxt.getText().toString();
xedit = xedit.trim();
File file;
file = new File(xedit);
StringBuilder text = new StringBuilder();
Log.d("fcheck",""+xedit);
try {
BufferedReader br = new BufferedReader(new FileReader(file)); //THIS LINE THROWS ERROR
Log.d("fcheck","f3"); //This line never got printed
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
resultView = (TextView) findViewById(R.id.header);
resultView.setText(text);
}
catch (IOException e) {
Log.d("File open error",""+e);
Toast.makeText(getApplicationContext(), "Error opening the file.", Toast.LENGTH_SHORT).show();
}
}
LogCat:
11-19 00:21:54.252: D/fcheck(5885): /storage/sdcard/mylibman.csv
11-19 00:21:54.272: D/File open error(5885): java.io.FileNotFoundException: /storage/sdcard/mylibman.csv: open failed: EACCES (Permission denied)
Make sure you have added the permission to read external storage in your manifest file.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
I was experiencing the same problem and it can be easily removed by following either of these steps:
1. Install your app by using -g if installing on Android N and O versions.
2. Grant permission manually
Settings->apps->"app_name"->Permissions->Enable Switch
For Both steps 1 and 2, define uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" and uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE" in AndroidManifest.xml
Like this :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="...">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!-- all permissions here -->
<application
...
Storage permission needs to be given by the user before accessing the functionality
Add Dependency:
dependencies:
permission_handler: ^5.0.1
Code Snippet:
var status = await Permission.storage.status;
if (status.isUndetermined) {
// You can request multiple permissions at once.
Map<Permission, PermissionStatus> statuses = await [
Permission.storage,
].request();
print(statuses[Permission.storage]); // it should print PermissionStatus.granted
}
I know there are a million threads on this, but I searched many of them with no help, I promise.
I am trying to use Places API to return results. I have tried the following:
Ensure a valid key (it works in this same app where I use a mapFragment, so I know the key is good. The places api was enabled at the time the key was generated.). In addition, I generated a new key and updated the app, map still works.
Make sure the search URL is formed correctly. I copied and pasted from the log into the browser, subbing the browser key, and the results returned appropriately.
Here is the manifest:
<permission
android:name="com.example.mapdemo.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.mapdemo.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.berrmal.locationbox.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>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIza**********************************Y" />
<service
android:name="com.berrmal.locationbox.LocationBoxService"
android:enabled="true"
android:exported="false" >
</service>
</application>
Here is the AsyncTask:
public class PlacesProvider extends AsyncTask<String, Void, ArrayList<Place>> {
//starting arg, progress update type, return from doInBack()
public PlacesProvider() {
}
public ArrayList<Place> doInBackground(String... args) {
//args[0] = search URL
Log.d("lbServ","doing in background");
ArrayList<Place> resultList = new ArrayList<Place>();
DLJSON dLJSON = new DLJSON();
try {
resultList = dLJSON.getResults(args[0]);
} catch (UnsupportedEncodingException uee) {
Log.d("lbServ","unsupp encode ex");
} catch (IOException ioe) {
Log.d("lbServ","IO exception");
} catch (IllegalStateException ils) {
Log.d("lbserv","iill state exception");
ils.printStackTrace();
} catch (Exception ex) {
Log.d("lbServ", "unknown exception in dlJson");
}
if (resultList == null) {
Log.d("lbServ","resultList is null");
}
return resultList;
}
protected void onPostExecute(ArrayList<Place> result) {
Log.d("lbServ","onnPostExecute");
placesList = result;
//TODO do something with the result, i.e. send it to MainActivity via instance that bound to server
Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
//resultIntent.setComponent(new ComponentName("com.berrmal.locationbox", "MainActivity"));
resultIntent.putExtra("SearchSuccess", true);
resultIntent.putExtra("searchID", 1);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(resultIntent);
Log.d("lbServ","service suicide");
stopSelf();
}
And the JSON querier/parser
public ArrayList<Place> getResults(String searchURL) throws UnsupportedEncodingException, IOException, IllegalStateException{
try {
url = new URL(searchURL);
Log.d("lbDLJSON",url.toString());
} catch (Exception ex) {
Log.d("lbDLJSON", "malformed URL");
}
try {
urlConn = (HttpsURLConnection) url.openConnection();
Log.d("dlJson","url connection open");
is = new BufferedInputStream(urlConn.getInputStream());
Log.d("dljson","buffered stream open");
} catch (IOException ioe) {
Log.d("lbDLJSON", "io exception");
} catch (Exception e) {
Log.d("lbDLJSON", "that other exception");
}
jsonReader = new JsonReader(new InputStreamReader(is, "UTF-8"));
Log.d("lbjson","json and inputstream readers exists");
resultList = new ArrayList<Place>();
jsonReader.beginObject();
Log.d("lbjson", "top level object open");
while (jsonReader.hasNext()) {
String name = jsonReader.nextName().toString();
if (name.equals("results")) {
jsonReader.beginArray();
while (jsonReader.hasNext()); {
//resultList.add(placeBuilder(jsonReader));
Log.d("lbjson", "results were null");
}
jsonReader.endArray();
} else if (name.equals("status")){
statusCode = jsonReader.nextString().toString();
Log.d("dljson", "status code: " + statusCode);
} else {
Log.d("lbjson", "skipped " + name);
jsonReader.skipValue();
}
}
jsonReader.endObject();
Log.d("lbDLJSON", "top level JSON object closed");
jsonReader.close();
urlConn.disconnect();
return resultList;
//Log.d("lbjson", "");
}
LogCat output:
05-24 16:04:07.859: D/lbServ(19523): search
05-24 16:04:07.859: D/lbServ(19523): executeAsyncTask
05-24 16:04:07.859: D/lbServ(19523): doing in background
05-24 16:04:07.859: D/lbDLJSON(19523): https://maps.googleapis.com/maps/api/place/nearbysearch/json?key=AIza***************************Y&location=34.0937751,-117.6730797&radius=15000&sensor=true&keyword=food
05-24 16:04:07.859: D/dlJson(19523): url connection open
05-24 16:04:08.199: D/dljson(19523): buffered stream open
05-24 16:04:08.199: D/lbjson(19523): json and inputstream readers exists
05-24 16:04:08.199: D/lbjson(19523): top level object open
05-24 16:04:08.199: D/lbjson(19523): skipped html_attributions
05-24 16:04:08.199: D/lbjson(19523): results were null
05-24 16:04:08.199: D/dljson(19523): status code: REQUEST_DENIED
05-24 16:04:08.199: D/lbDLJSON(19523): top level JSON object closed
05-24 16:04:08.199: D/lbServ(19523): onnPostExecute
05-24 16:04:08.220: D/lbServ(19523): service suicide
I can post the URL generating method, but as you see the URL is formed appropriately from the log.
I have been googling and trying things for several hours, so I'm really stumped. I don't understand why I can paste the same link into the browser, change the key to the browser key, and get valid results (8.3kb), but the app here returns the following 85b result:
{
"html_attributions" : [],
"results" : [],
"status" : "REQUEST_DENIED"
}
I get this same request denied result when clicking the "try it out!" link on the api console list of services, but if I make the URL manually I get valid results...?
EDIT:
I kept the android app key in the manifest, for maps permission, but in the HTTP request, I changed the key to the browser key, and got successful results on the places query. I don't know why, it doesn't really make sense. I'm a bit afraid that its a breach of the TOS, but I'm not really sure. Is this indicative of something I'm doing wrong? Or does anyone know a way to contact Google to report it? Or was I supposed to use both keys all along?
OK, as best I can tell, the issue was solved by using both keys. I use the Android API key in my manifest, this gets the mapFragment working correctly.
To get the places request to come back "OK" and not "REQUEST_DENIED", I had to use the browser key from the Google API console. I assume, because my app constructs a search URL and uses the HTTP connection to send and receive, google's server thinks its a browser rather than an app. I don't know if this is correct usage, if I get a nastygram from Google I'll update the thread.
i am new android developer
when ever i run this code i get this error "Source not found." just when it reaches the
url.openStream()
any idea how to fix this?
try {
URL url = new URL("http://pollsdb.com/test.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
<uses-permission
android:name="android.permission.INTERNET" />
add that under your first manifest tag in your AndroidManifest.xml
I have the same problem too. But now, i have been solved this problem by reference http://developer.android.com/guide/components/processes-and-threads.html
about the thread use.
You need to create a worker thread to work for open the URL stream rather than using the main thread(UI thread).
Of course, you also need to add
<uses-permission android:name="android.permission.INTERNET" />
in your AndroidManifest.xml