Related
I'm trying to access the hidden API for Phone.class to switch the preferred network mode via reflection.
I know this is not safe for porting to other android versions/roms and requires a system app to hold permission WRITE_SECURE_SETTINGS.
I Already managed to switch data via reflection and toggle gps via Settings.Secure.putString() by moving my app to system partition, so i think this should work too.
Does anyone have experience with reflection and/or root and is willing to help?
Of course I will share all my code/findings here.
Thanks in advance!
Links:
http://stackoverflow.com/questions/8607263/android-4-0-4g-toggle
http://stackoverflow.com/questions/5436251/how-to-access-setpreferrednetworktype-in-android-source
You can achieve this with a simple sqlite3 query instead of bothering with java reflection
Here's how :
In a terminal :
To enable 2G only
Code:
su
sqlite3 /data/data/com.android.providers.settings/databases/settings.db
insert into global values(null, 'preferred_network_mode', 1);
.exit
To enable 2G & 3G :
Code:
su
sqlite3 /data/data/com.android.providers.settings/databases/settings.db
insert into global values(null, 'preferred_network_mode', 0);
.exit
In java :
Example to enable 2G only (just replace the 1 with a 0 in the insert into to enable 2G & 3G)
Code:
try {
Process process = null;
process = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(
process.getOutputStream());
os.writeBytes("sqlite3 /data/data/com.android.providers.settings/databases/settings.db" + "\n");
os.writeBytes("insert into global values(null, 'preferred_network_mode', 1);" + "\n");
os.writeBytes(".exit" + "\n");
os.writeBytes("exit\n");
os.flush();
process.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
It might require a reboot to be active though, not sure
If it doesn't work on your rom (tested on cm10.1), it might be a different row name, try investigating your settings.db like this :
Code:
sqlite3 /data/data/com.android.providers.settings/databases/settings.db
.tables [COLOR="Green"]// returns all the tables[/COLOR]
select * from [I]tablename[/I]; [COLOR="green"]// in cm10.1 it's in [I]global[/I] but otherwise look in [I]secure[/I] and/or [I]system[/I]
// this command returns all the rows from the selected table, the names are usually explicit, so you should find the setting you're looking for[/COLOR]
Then, when you found it :
Code:
insert into [I]tablename[/I] values(null, [I]'row name'[/I], value);
Thanks, this is very helpful!
I think you are right, one will need to tell the system to update the settings or send a broadcast that this setting has changed (like for airplane mode).
I will look at the CM sources to find out what i can do.
superkoal said:
Thanks, this is very helpful!
I think you are right, one will need to tell the system to update the settings or send a broadcast that this setting has changed (like for airplane mode).
I will look at the CM sources to find out what i can do.
Click to expand...
Click to collapse
Glad it helped.
If you manage to find a way to make the settings read the db without a reboot, please share your findings, would be very useful.
Androguide.fr said:
Glad it helped.
If you manage to find a way to make the settings read the db without a reboot, please share your findings, would be very useful.
Click to expand...
Click to collapse
Of course i will!
Buddy... you can toggle network mode with intent, no root needed, nor permissions!!
Here´s entire sample:
Code:
package com.serajr.togglenetworkmode;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.provider.Settings.SettingNotFoundException;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bnt = (Button) findViewById(R.id.button1);
bnt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// toggle
toggleNetworkMode();
}
});
}
private void toggleNetworkMode() {
int mode = getCurrentNetworkMode() + 1;
if (mode > 2) {
mode = 0;
}
// 0 = 3G_ONLY
// 1 = 3GSM_ONLY
// 2 = 3G_PREFERRED
// change mode
Intent intent = new Intent("com.android.phone.CHANGE_NETWORK_MODE");
intent.putExtra("com.android.phone.NEW_NETWORK_MODE", mode);
sendBroadcast(intent);
}
private int getCurrentNetworkMode() {
try {
int current = Secure.getInt(getContentResolver(), "preferred_network_mode");
return current;
} catch (SettingNotFoundException ex) {
return 0;
}
}
}
Try it and tell me later!!!
Thanks, but this will only work if your phone.apk has an exported receiver for this intent.
This is only the case if you or your rom dev modded it to be so.
Some custom ROMs also have this kind of "mod/bug" in the power widget, allowing you to toggle gps.
I tried it with slim bean 4.2 build 3 on i9000 and as expected it didn't work (and so will most likely in CM10.1 too).
Just too good to be true!
If youre following the root method Use RootTools for that
sak-venom1997 said:
If youre following the root method Use RootTools for that
Click to expand...
Click to collapse
Thanks, I already do.
Really helpful library!
And yes, I will do it by sql injection to settings.db
I only need to figure out what broadcasts have to be sent / methods called and if this is possible.
Argh I am kinda lost in CM sources.
Can anyone point me to the place where this is handled?
I managed to toggle flight mode by using this in a SU shell:
Code:
if(settingenabled)
{
executeCommand("settings put global airplane_mode_on 1");
executeCommand("am broadcast -a android.intent.action.AIRPLANE_MODE --ez state true");
}
else
{
executeCommand("settings put global airplane_mode_on 0");
executeCommand("am broadcast -a android.intent.action.AIRPLANE_MODE --ez state false");
}
Interstingly enough it didn't work if i manually injected the value and then sent the broadcast.
I have no idea why.
So atm I'm trying to do the same thing for preferred_network_mode. I can write the value to settings.db, but I just don't know what i have to do to make the system apply the setting yet.
EDIT: shell binary "settings" only works in android 4.2 (and probably upwards)
So i finally found it in CM Sources.
Seems like we need to get the currently running Instance of the Phone class to notify it about the change.
Also seems like we are back to reflection, as this is an internal system class.
I also killed com.android.phone process after updating the setting, but that didn't change anything.
EDIT:
1st step towards reflection:
I figured out that i need a jar file from the cm build to use system classes via reflection.
Does anyone have more information about this?
superkoal said:
So i finally found it in CM Sources.
Seems like we need to get the currently running Instance of the Phone class to notify it about the change.
Also seems like we are back to reflection, as this is an internal system class.
I also killed com.android.phone process after updating the setting, but that didn't change anything.
EDIT:
1st step towards reflection:
I figured out that i need a jar file from the cm build to use system classes via reflection.
Does anyone have more information about this?
Click to expand...
Click to collapse
Just a far fetched guess, but maybe try to add /system/framework/framework.jar from your rom to your app's build path
Is a reboot that unacceptable in your case ?
Maybe it's just the challenge, but i wanna change it like every other setting
A reboot is very far from what i call comfortable
superkoal said:
Maybe it's just the challenge, but i wanna change it like every other setting
A reboot is very far from what i call comfortable
Click to expand...
Click to collapse
Yeah, I get what you mean^^^
Here's a good (but old, 2009^^) official Android tutorial from the Android devs on reflection if it can help you : http://android-developers.blogspot.fr/2009/04/backward-compatibility-for-android.html
So i got some news
1. This setting is heavily protected by android system and can only be modified by the phone process itself
2. Some roms have a modified phone apk listening to a broadcast, enabling 3rd party apps to toggle
http://forum.xda-developers.com/showthread.php?t=1731187
3. His Majesty Chainfire started an app project which could amongst other features also toggle 2g/3g, but he gave up development. Regarding 2g/3g he implemented several methods, one of them being RIL injection, which he described as a really hard hack and highly experimental.
http://forum.xda-developers.com/showthread.php?t=807989
Seems this task is not that easy
But i found out that tasker can toggle 2g/3g on my phone (running slim bean 4.2.2), this is when i found out about the modified phone.apk from 2). So I'mcomfortable that it's working on my phone and i can at least develop an app for myself
Sent from my GT-I9000 using xda app-developers app
Hey XDA, this is my first guide and first proper contribution to the community!
I’m writing this because I've seen many people ask a variation of the question: “How can my app get information from a database?”
This guide is intended for those who have created their first app – it is assumed you have a working development environment and are reasonable comfortable with the Android SDK and Java. I'm also assuming little to no knowledge of PHP and MYSQL
This guide walks you through:
Setting up a database and a PHP script
Testing the server
Accessing it from Android.
To make it relevant, we're going to use data that we might see in an actual app: First & Last Name, Age and Points.
Requirements:
Android Device*
Computer*
Apache/PHP/MySQL Server – I use WAMP (for Windows) (PHP v 5.4)
Postman Rest Client for Google Chrome
(*Both must be connected to the same network!)
This guide will help you setup a local server. If you want to host your script and database online, you will have to purchase paid hosting.
Let's get started!
First off, what is a RESTful service?
According to Wikipedia: A RESTful web API (also called a RESTful web service) is a web API implemented using HTTP and REST principles.
How it works:
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
A breakdown of the steps:
The client makes a request using a HTTP POST to a server
The PHP script queries the MYSQL server
The PHP script gets the SQL data
The PHP script puts the data into an array and assigns keys for the values. The script then outputs the data as a JSON array. JSON (JavaScript Object Notation) is a standard for data exchange, and formats the data in a way both humans and computers can easily read.
The app parses the JSON and displays the data.
Code!
Part 1: The Server
We’re going to start by setting up the server!
Install WAMP server. Leave the settings at the default values.
Start WAMP server and let it come online.
Try and open http://localhost/phpmyadmin/ - if you installed it correctly, you should be greeted by the phpMyAdmin welcome screen. We're going to be using phpMyAdmin to create our database.
Creating the Database:
Create a database called ‘mytestdatabase’. Now click the SQL tab, paste in the following SQL Code and hit run. This will create a test table called ‘users’ and fill it with data.
The table contains 5 columns: id, FirstName, LastName, Age, Points. It has 6 rows of sample data.
SQL Code:
Code:
-- phpMyAdmin SQL Dump
-- version 3.5.1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Jun 15, 2013 at 10:07 PM
-- Server version: 5.5.24-log
-- PHP Version: 5.3.13
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET [user=714032]@old_[/user][email protected]@CHARACTER_SET_CLIENT */;
/*!40101 SET [user=714032]@old_[/user][email protected]@CHARACTER_SET_RESULTS */;
/*!40101 SET [user=714032]@old_[/user][email protected]@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `MyTestDatabase`
--
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`FirstName` text NOT NULL,
`LastName` text NOT NULL,
`Age` int(11) NOT NULL,
`Points` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `FirstName`, `LastName`, `Age`, `Points`) VALUES
(1, 'John', 'Doe', 25, 61),
(2, 'Glen', 'Willis', 55, 3145),
(3, 'Helen', 'Cook', 35, 1232),
(4, 'Karen', 'Johnson', 20, 6456),
(5, 'Bill', 'Cooper', 60, 3856),
(6, 'Mary', 'Gomez', 30, 5422);
/*!40101 SET CHARACTER_SET_CLIENT [user=714032]@old_[/user]CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS [user=714032]@old_[/user]CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION [user=714032]@old_[/user]COLLATION_CONNECTION */;
Your database should now look like this:
We’re now ready to move on to the PHP!
Open up your WWW directory (C:\wamp\www) and create a new folder called ‘clientservertest’. In this folder, create a file called ‘login.php’.
Paste the following code into the file. (The PHP code is commented so you can follow what is going on)
PHP:
<?php
#Ensure that the client has provided a value for "FirstNameToSearch"
if (isset($_POST["FirstNameToSearch"]) && $_POST["FirstNameToSearch"] != ""){
#Setup variables
$firstname = $_POST["FirstNameToSearch"];
#Connect to Database
$con = mysqli_connect("localhost","root","", "mytestdatabase");
#Check connection
if (mysqli_connect_errno()) {
echo 'Database connection error: ' . mysqli_connect_error();
exit();
}
#Escape special characters to avoid SQL injection attacks
$firstname = mysqli_real_escape_string($con, $firstname);
#Query the database to get the user details.
$userdetails = mysqli_query($con, "SELECT * FROM users WHERE FirstName = '$firstname'");
#If no data was returned, check for any SQL errors
if (!$userdetails) {
echo 'Could not run query: ' . mysqli_error($con);
exit;
}
#Get the first row of the results
$row = mysqli_fetch_row($userdetails);
#Build the result array (Assign keys to the values)
$result_data = array(
'FirstName' => $row[1],
'LastName' => $row[2],
'Age' => $row[3],
'Points' => $row[4],
);
#Output the JSON data
echo json_encode($result_data);
}else{
echo "Could not complete query. Missing parameter";
}
?>
Testing the Script:
Try accessing http://localhost/clientservertest/login.php from your browser. Do you get this message:
"Could not complete query. Missing parameter"
Then it’s working! The script is looking for a POST variable called “FirstNameToSearch” – we didn't provide any, so it did't work!
To finish testing the script, open the Postman-REST client.
Set it up like so:
Request URL: http://localhost/clientservertest/login.php
Type: POST
Key: FirstNameToSearch
Value: John
Hit send, and you should see this:
Code:
{"FirstName":"John","LastName":"Doe","Age":"25","Points":"61"}
Congrats – your server just returned a result! Try some of the other names in the database (Glen, Helen, Karen, Bill, Mary) and see how their data is returned.
Note: Before we move on to the Android section, we’re going to have to put our WAMP server online. Click the WAMP icon in the taskbar and select 'Put Online'.
Find your computers local network IP address and insert it into the URL like so: http://192.168.1.112/clientservertest/login.php
You should be able to access the script. If this doesn't work, try turning off your firewall - it could be blocking the server.
Part 2: Android
We’re now going to use our Android device to access the web server instead of the Postman client.
I'm not going to go into detail with the boilerplate UI code - I've attached the source code to this post so you can download the project files and browse through them.
Note: Android 3.x+ cannot perform Network operations on the main thread. To solve this, we have to multithread our program. To keep this as simple as possible, we’re going to use an AsyncTask. Again, the code for this can be found in the project download.
Inside of the AsyncTask, we have the most important code - where we create and execute a HTTP POST in Java.
Creating and Executing a HTTP POST in Java:
We have to first setup the name-value pairs for our POST variables. In this case, we use "FirstNameToSearch" as our Key.
Code:
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("FirstNameToSearch", strNameToSearch));
The following code sets up connection timeouts (15 seconds) and creates a HttpClient and HttpPost pointing to our url (http://192.168.1.112/clientservertest/login.php)
Code:
//Create the HTTP request
HttpParams httpParameters = new BasicHttpParams();
//Setup timeouts
HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
HttpConnectionParams.setSoTimeout(httpParameters, 15000);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost("http://192.168.1.112/clientservertest/login.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
The following code executes the POST, gets the result and converts it to a string:
Code:
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
Finally, the following code creates a JSON object from the result string and extracts our data:
Code:
// Create a JSON object from the request response
JSONObject jsonObject = new JSONObject(result);
//Retrieve the data from the JSON object
strFirstName = jsonObject.getString("FirstName");
strLastName = jsonObject.getString("LastName");
intAge = jsonObject.getInt("Age");
intPoints = jsonObject.getInt("Points");
That's it. It's so simple!
Where do we take it from here?
This combination of PHP/MYSQL is quite powerful. I'd recommend that you learn more about these technologies and build upon the demo in this guide. PHP Tutorials & MySQL Tutorials
Ideas for practice apps:
Online notes application - Sync your notes to the cloud
Build an Activation Server - Users can activate an app with a key
Feedback
Please feel free to leave any followup questions, comments or suggestions! I'll try my best to respond!
You can find the source code over at GitHub. Have fun! (If you fix a bug, please send a pull request)
Additional Information
Changelog
November 3, 2013
Added a link to the GitHub repository.
June 26, 2013
Updated PHP Code. It's more reliable and uses the newer MySQL APIs. Thanks to @dbarrera & @vijai2011
July 7, 2013
Updated the Android project and added Internet permissions (ClientServerRESTDemo v2.zip)
Thanks for this amazing guide but I have a issue.I have my own table and columns.So I changed your php code according to that and when I do a post query in rest,I get all null.But if I do the same in phpmyadmin,I have results.
This is what I get in postman:
Code:
{"pid":null,"name":null,"UID":null,"mobile":null,"description":null,"created_at":null,"updated_at":null}
attached the output of phpmyadmin.
And my phpcode:
Code:
<?php
#Setup variables
$firstname = $_POST["FirstNameToSearch"];
#Avoid SQL injection attacks
$firstname = mysql_real_escape_string($firstname);
#Connect to Database
$con = mysql_connect("localhost","user","pass");
if (!$con)
{
die('Could not connect');
}
#Select the test database
mysql_select_db("mydb", $con);
#Get the user details from the database
$userdetails = mysql_query("SELECT * FROM mytable WHERE name = '$firstname'");
#Catch any errors
if (!$userdetails) {
echo 'It seems the server is down.Please try later';
exit;
}
#Get the first row of the results
$row = mysql_fetch_row($userdetails);
#Build the result array (Assign keys to the values)
$result_data = array(
'pid' => $row[1],
'name' => $row[2],
'UID' => $row[3],
'mobile' => $row[4],
'description' => $row[5],
'created_at' => $row[6],
'updated_at' => $row[7],
);
#Output the JSON data
echo json_encode($result_data);
?>
Thanks for help.
Edit: just found that your app is missing internet permission in manifest
Code:
<uses-permission android:name="android.permission.INTERNET" />
:thumbup:
Thanks so much for this. I will try it out soon.
Sent from my HTC Explorer A310e using xda app-developers app
vijai2011 said:
Thanks for this amazing guide but I have a issue.I have my own table and columns.So I changed your php code according to that and when I do a post query in rest,I get all null.But if I do the same in phpmyadmin,I have results.
This is what I get in postman:
Code:
{"pid":null,"name":null,"UID":null,"mobile":null,"description":null,"created_at":null,"updated_at":null}
attached the output of phpmyadmin.
Thanks for help.
Click to expand...
Click to collapse
I was able to reproduce the null result - it means that the result was not available in the database. You'll want to double check the value you are passing to the script in Postman. (When I used 'FirstNameToSearch' and 'test' - I got a correct result. However, when I used 'testa', I got a null result.)
You can try adding this into the PHP script to catch this problem:
Code:
#Get the first row of the results
$row = mysql_fetch_row($userdetails);
[B]#Check to see if a result was returned.
if(!$row){
echo 'User does not exist';
exit;
}[/B]
I also noticed a few things in your PHP script:
In your screenshot, your table name appears to be 'Myapp', however in your PHP script, it looks like you are using 'mytable'
When you build the result array at the end, you are trying to access a column that doesn't exist:
This code tries to access an 8th column/index:
Code:
'pid' => $row[1],
'name' => $row[2],
'UID' => $row[3],
'mobile' => $row[4],
'description' => $row[5],
'created_at' => $row[6],
'updated_at' => $row[7],
You only have seven columns, so it should be:
Code:
'pid' => $row[0],
'name' => $row[1],
'UID' => $row[2],
'mobile' => $row[3],
'description' => $row[4],
'created_at' => $row[5],
'updated_at' => $row[6],
vijai2011 said:
Edit: just found that your app is missing internet permission in manifest
Code:
<uses-permission android:name="android.permission.INTERNET" />
Click to expand...
Click to collapse
Good catch - Thanks! I'll update the project asap.
Alkonic said:
I was able to reproduce the null result - it means that the result was not available in the database. You'll want to double check the value you are passing to the script in Postman. (When I used 'FirstNameToSearch' and 'test' - I got a correct result. However, when I used 'testa', I got a null result.)
:snip:
Good catch - Thanks! I'll update the project asap.
Click to expand...
Click to collapse
That is not a error in table name because I just wanted to hide it out here but actually it got revealed in the screenshot .No issues will try your php code and correct my json array too.thanks
Sent from my GT-N7000 using xda app-developers app
For some reason,the problem was caused by the mysql_real_escape_string.I commented that line and it is working now.
vijai2011 said:
For some reason,the problem was caused by the mysql_real_escape_string.I commented that line and it is working now.
Click to expand...
Click to collapse
Now that's interesting.. I've never experienced a problem with that before.
I took a look at the PHP docs and found that mysql_real_escape_string() is depreciated - that could be contributing to the problem. I'll investigate this further and adjust the guide as necessary.
Thanks for sharing your solution!.
Alkonic said:
Now that's interesting.. I've never experienced a problem with that before.
I took a look at the PHP docs and found that mysql_real_escape_string() is depreciated - that could be contributing to the problem. I'll investigate this further and adjust the guide as necessary.
Thanks for sharing your solution!.
Click to expand...
Click to collapse
Maybe you are using ancient php module .BTW Can I also put data into tables using your php and slightly modifying "mysql_query" and using post?Or should I use put along with mysql_query?If later is the solution,could give me the snippet of how a put variable looks?because I dono php and I was waiting for someone to write this guide because before I was connecting to db with JDBS which isnt safe.Thanks and sorry for the trouble.
Edit: I got it to work like I said.But only issue is the created at and updated at time stamp which is not the part of php nor the app.I will correct it from mysql.Thanks once again.Will be happy to trouble you soon lol...No dont take it serious BTW
vijai2011 said:
Maybe you are using ancient php module .BTW Can I also put data into tables using your php and slightly modifying "mysql_query" and using post?Or should I use put along with mysql_query?If later is the solution,could give me the snippet of how a put variable looks?because I dono php and I was waiting for someone to write this guide because before I was connecting to db with JDBS which isnt safe.Thanks and sorry for the trouble.
Edit: I got it to work like I said.But only issue is the created at and updated at time stamp which is not the part of php nor the app.I will correct it from mysql.Thanks once again.Will be happy to trouble you soon lol...No dont take it serious BTW
Click to expand...
Click to collapse
Ha you beat me to it! I'll definitely try and add a section into the guide about updating tables. I appreciate your feedback on the guide, and I'm glad it helped you. Feel free to trouble me
Perfect! Just what i needed for my next week exam!
Sent from my GT-S5830M using Tapatalk 2
Super, thx!
But please tell me what I'm doing wrong.
Code:
HttpResponse response = httpclient.execute(httppost); //throw...
i save errors in log (attached)
pls help ;(
objaa said:
Super, thx!
But please tell me what I'm doing wrong.
Code:
HttpResponse response = httpclient.execute(httppost); //throw...
i save errors in log (attached)
pls help ;(
Click to expand...
Click to collapse
You are doing something on the main thread which actually has to be done in a different thread.I suspect its at line #119.If you show the entire code,somebody might point it out easily for you
Sent from my GT-N7000 using xda app-developers app
vijai2011 said:
You are doing something on the main thread which actually has to be done in a different thread.I suspect its at line #119.If you show the entire code,somebody might point it out easily for you
Sent from my GT-N7000 using xda app-developers app
Click to expand...
Click to collapse
ok, all code:
package com.nsp.obja;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;
public class MainActivity extends Activity {
@override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myscreen);
post();
}
@override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
void post()
{
try
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("FirstNameToSearch", "wow"));
//Create the HTTP request
HttpParams httpParameters = new BasicHttpParams();
//Setup timeouts
HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
HttpConnectionParams.setSoTimeout(httpParameters, 15000);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost("http://www.xda-developers.com/");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
Toast.makeText(this, result.length(), Toast.LENGTH_LONG).show();
}
catch(Exception e)
{
Log.e("ClientServerDemoX", "Error: ", e);
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
objaa said:
ok, all code:
<!----Snip!---->
Click to expand...
Click to collapse
Do post() in async because it has to do http request which needs to be done in another thread.
vijai2011 said:
You are doing something on the main thread which actually has to be done in a different thread.I suspect its at line #119.If you show the entire code,somebody might point it out easily for you
Sent from my GT-N7000 using xda app-developers app
Click to expand...
Click to collapse
vijai2011 said:
Do post() in async because it has to do http request which needs to be done in another thread.
Click to expand...
Click to collapse
hoooww :crying::crying:
Thanks, I figured out and got the code page of our glorious forum
I'm having an issue while testing the Query... I'm using Firefox and using RESTClient for debugging... and testing whatever value, db always responds null (See attachment)...
dbarrera said:
I'm having an issue while testing the Query... I'm using Firefox and using RESTClient for debugging... and testing whatever value, db always responds null (See attachment)...
Click to expand...
Click to collapse
Exactly what I experienced first time.Try after commenting the line which prevents mysql injection and see if it works.If you run latest mysql,the chances are probably that its the issue
vijai2011 said:
Exactly what I experienced first time.Try after commenting the line which prevents mysql injection and see if it works.If you run latest mysql,the chances are probably that its the issue
Click to expand...
Click to collapse
Already tried that... No go... Had to write the whole thing using w3schools example code as base... Just resolved a couple minutes ago and completed the project (it can be viewed @ Github:CardManager (App) and cardmanager_json (Web Service, only principal.php is the one handling the whole thing))...
Maybe a good add to the tutorial would be to have a config.php file with the user, passwd, database and table data calling it through require_once()... The DBConexion and DBGestion files (in my github) are supposed to do that, but didn't work either (hence doing the principal.php code all over again)...
dbarrera said:
Already tried that... No go... Had to write the whole thing using w3schools example code as base... Just resolved a couple minutes ago and completed the project (it can be viewed @ Github:CardManager (App) and cardmanager_json (Web Service, only principal.php is the one handling the whole thing))...
Maybe a good add to the tutorial would be to have a config.php file with the user, passwd, database and table data calling it through require_once()... The DBConexion and DBGestion files (in my github) are supposed to do that, but didn't work either (hence doing the principal.php code all over again)...
Click to expand...
Click to collapse
Interesting.. I'll take a look at at your script, revisit the W3 tutorials, and then re-write mine. It's really rudimentary and tends to fail easily. I wanted to write about the config.php, however, I also wanted to keep this guide as simple as possible for newer users. Maybe I'll add in an advanced section.
I'll update the guide in a few days, as I'm right in the middle of exams :/
Thanks for the feedback!
I was able to install the HTC Sprint Diagnosis app on my Nokia Lumia 1520 and also have the HTC CSDDiag app installed.
Interesting Part : I was able to run CSDDiag on the Lumia handset and all tests were completed.
Now what i would like to know is how do i run this code in the Native Toast Launcher :
Code:
// Type: DiagnosticTool_Sprint.MainPage
// Assembly: DiagnosticTool_Sprint, Version=1.3.2319.13220, Culture=neutral, PublicKeyToken=null
// MVID: B9415712-08FA-4E66-9A8E-A318594B96CD
// Assembly location: C:\Users\Joshua\Desktop\SPRINT\Data\programs\{E69A2877-59B8-43ED-898D-554FBC4B8B2B}\Install\DiagnosticTool_Sprint.dll
using HTCLogUtil;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System;
using System.Diagnostics;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Windows.System;
namespace DiagnosticTool_Sprint
{
public class MainPage : PhoneApplicationPage
{
public static string DIALER_CODE_CT_LAB = "0000";
public static string DIALER_CODE_EMBEDDED_TOOL = "634";
public static string DIALER_CODE_SERVICE_TOOL_1 = "778";
public static string DIALER_CODE_SERVICE_TOOL_2 = "786";
public static string DIALER_CODE_VZW_TOOL = "522";
public static string DIALER_CODE_CSDIAG_TOOL = "3424";
public static string DIALER_CODE_DEBUG = "33284";
public static string DIALER_CODE_ZONE_TOOL = "611";
public static string DIALER_CODE_DIAG = "3424";
public static string DIALER_CODE_SCRTN = "72786";
public static string DIALER_CODE_DATA = "3282";
public static string DIALER_CODE_UPDATE = "873283";
public static string strUri;
internal Grid LayoutRoot;
internal StackPanel TitlePanel;
internal Grid ContentPanel;
private bool _contentLoaded;
static MainPage()
{
}
public MainPage()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
DiagDebugLogUtil.DiagDebugLog(LOG_SEVERITY.LOG_INFO, "[PC Tools]: OnNavigatedTo()++++", new object[0]);
try
{
if (!PhoneApplicationService.Current.State.ContainsKey("VersionNumber"))
PhoneApplicationService.Current.State.Add("VersionNumber", (object) ((object) Assembly.GetExecutingAssembly().GetName().Version).ToString());
string str = "634";
if (this.NavigationContext.QueryString.TryGetValue("DialString", out str))
{
if (str.Equals(MainPage.DIALER_CODE_SERVICE_TOOL_1) || str.Equals(MainPage.DIALER_CODE_SERVICE_TOOL_2) || (str.Equals(MainPage.DIALER_CODE_DATA) || str.Equals(MainPage.DIALER_CODE_SCRTN)))
this.NavigationService.Navigate(new Uri("/ServiceToolLib;component/View/PageLists.xaml", UriKind.Relative));
else if (str.Equals(MainPage.DIALER_CODE_EMBEDDED_TOOL) || str.Equals(MainPage.DIALER_CODE_DEBUG))
{
if (!PhoneApplicationService.Current.State.ContainsKey("DialString"))
PhoneApplicationService.Current.State.Add("DialString", (object) "634");
this.NavigationService.Navigate(new Uri("/EmbeddedTool;component/EmbMainPage.xaml", UriKind.Relative));
}
else if (str.Equals(MainPage.DIALER_CODE_CSDIAG_TOOL))
this.NavigationService.Navigate(new Uri("/RedirectionTool;component/RedirectionPage.xaml?tool=CSDDiag", UriKind.Relative));
else if (str.Equals(MainPage.DIALER_CODE_VZW_TOOL))
this.NavigationService.Navigate(new Uri("/RedirectionTool;component/RedirectionPage.xaml?tool=LabApp", UriKind.Relative));
else if (str.Equals(MainPage.DIALER_CODE_ZONE_TOOL))
{
if (!App.bNoBackForLaunchAPP)
{
MainPage.strUri = "sprintzone:callintercept?code=" + str;
App.bNoBackForLaunchAPP = true;
this.LaunchSprintAP();
}
}
else if (str.Equals(MainPage.DIALER_CODE_UPDATE))
{
if (!App.bNoBackForLaunchAPP)
{
MainPage.strUri = "ms-settings-networkprofileupdate:";
App.bNoBackForLaunchAPP = true;
this.LaunchUpdate();
}
}
else
this.NavigationService.Navigate(new Uri("/EmbeddedTool;component/EmbMainPage.xaml", UriKind.Relative));
}
else
this.NavigationService.Navigate(new Uri("/EmbeddedTool;component/EmbMainPage.xaml", UriKind.Relative));
}
catch (Exception ex)
{
DiagDebugLogUtil.DiagDebugLog(LOG_SEVERITY.LOG_ERROR, "[MainPage] Get Exception msg :" + ((object) ex.Message).ToString(), new object[0]);
this.NavigationService.Navigate(new Uri("/EmbeddedTool;component/EmbMainPage.xaml", UriKind.Relative));
}
DiagDebugLogUtil.DiagDebugLog(LOG_SEVERITY.LOG_INFO, "[PC Tools]: OnNavigatedTo()----", new object[0]);
}
public async void LaunchUpdate()
{
Uri uri = new Uri(MainPage.strUri);
int num = await Launcher.LaunchUriAsync(uri) ? 1 : 0;
}
public async void LaunchSprintAP()
{
Uri uri = new Uri(MainPage.strUri);
int num = await Launcher.LaunchUriAsync(uri) ? 1 : 0;
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
this.RemoveEntry("MainPage");
}
private void RemoveEntry(string sPageName)
{
foreach (JournalEntry journalEntry in this.NavigationService.BackStack)
{
if (journalEntry.Source.ToString().Contains(sPageName))
{
this.NavigationService.RemoveBackEntry();
break;
}
}
}
[DebuggerNonUserCode]
public void InitializeComponent()
{
if (this._contentLoaded)
return;
this._contentLoaded = true;
Application.LoadComponent((object) this, new Uri("/DiagnosticTool_Sprint;component/MainPage.xaml", UriKind.Relative));
this.LayoutRoot = (Grid) this.FindName("LayoutRoot");
this.TitlePanel = (StackPanel) this.FindName("TitlePanel");
this.ContentPanel = (Grid) this.FindName("ContentPanel");
}
}
}
I can reach the Main page by issuing :
Code:
app://E69A2877-59B8-43ED-898D-554FBC4B8B2B/_default
However I would like to run the Dialer commands to see if I can mod anything else on the phone. Could some with good brain explain how this will be possible.
I have tried install other platform Diag tools but was only able to install the two above using fiddler ( thanks ngame for your tutorial )
Who did you do that ? I Try it many times before to install these aps on RM-821 Nokia Lumia 920 but didn't work !
how did you do that ? Could you please P.M Me ?
ngame said:
Who did you do that ? I Try it many times before to install these aps on RM-821 Nokia Lumia 920 but didn't work !
how did you do that ? Could you please P.M Me ?
Click to expand...
Click to collapse
It wasnt hard to install those apps. Just followed the fiddler tutorial posted.
Then I connected the phone and installed SysPushApp onto the device and did an update for the SysPushApp to get the non_OEM files of Samsung and HTC . I couldnt install Samsung Diagnosis as it wasn't letting nor was I able to install HTC Hub ( I dont know why, may be they check some .dll specific to them in the phone before install ) .
Change the oSession in fiddler config file to the specific OEM you want to install the app. Example for HTC[ ->
oSession (NOKIA)
(NOKIA), (HTC) /B]
Mt device is Dev-Unlock.
tids2k said:
It wasnt hard to install those apps. Just followed the fiddler tutorial posted.
Then I connected the phone and installed SysPushApp onto the device and did an update for the SysPushApp to get the non_OEM files of Samsung and HTC . I couldnt install Samsung Diagnosis as it wasn't letting nor was I able to install HTC Hub ( I dont know why, may be they check some .dll specific to them in the phone before install ) .
Change the oSession in fiddler config file to the specific OEM you want to install the app. Example for HTC[ ->
oSession (NOKIA)
(NOKIA), (HTC) /B]
Mt device is Dev-Unlock.
Click to expand...
Click to collapse
Samsung diagnosis already removed from wp store so you can't install it easy
and diagnosis you can see in store may different from one in Samsung phones! If you check file sizes you will get what i say
Most of HTC apps only can install ID_Resolution_HD720p and WVGA devices i don't know how is it possible to deploy them on 1080 devices
maybe MS accept this resolution for all apps because the old apps have to add 1080 support?
ngame said:
Samsung diagnosis already removed from wp store so you can't install it easy
and diagnosis you can see in store may different from one in Samsung phones! If you check file sizes you will get what i say
Most of HTC apps only can install ID_Resolution_HD720p and WVGA devices i don't know how is it possible to deploy them on 1080 devices
maybe MS accept this resolution for all apps because the old apps have to add 1080 support?
Click to expand...
Click to collapse
correct some Samsung apps are Unpublished like Diagnosis. Can you tell me how to run the above codes in Native Launcher .. what to type after app://GUID/??
tids2k said:
correct some Samsung apps are Unpublished like Diagnosis. Can you tell me how to run the above codes in Native Launcher .. what to type after app://GUID/??
Click to expand...
Click to collapse
I don't have this xaps but you have to use .Net Reflector 8 or any .net Decompiler then u can see all hidden xamls after _default you have to enter a #/ then dll name without it's dll them a ; and then folder and xaml address
example :
app://GUID/_default#/dllname;Pages/ExamplePage.xaml
ngame said:
I don't have this xaps but you have to use .Net Reflector 8 or any .net Decompiler then u can see all hidden xamls after _default you have to enter a #/ then dll name without it's dll them a ; and then folder and xaml address
example :
app://GUID/_default#/dllname;Pages/ExamplePage.xaml
Click to expand...
Click to collapse
here is the XAP
tids2k said:
here is the XAP
Click to expand...
Click to collapse
app://e69a2877-59b8-43ed-898d-554fbc4b8b2b/_default
app://e69a2877-59b8-43ed-898d-554fbc4b8b2b/_default#/DiagnosticTool_Sprint;Component/app.xaml
app://e69a2877-59b8-43ed-898d-554fbc4b8b2b/_default#/DiagnosticTool_Sprint;Component/MainPage.xaml
app://e69a2877-59b8-43ed-898d-554fbc4b8b2b/_default#/EmbeddedTool;Component/app.xaml
app://e69a2877-59b8-43ed-898d-554fbc4b8b2b/_default#/EmbeddedTool;Component/dmswitchpage.xaml
app://e69a2877-59b8-43ed-898d-554fbc4b8b2b/_default#/EmbeddedTool;Component/embcheckspc.xaml
app://e69a2877-59b8-43ed-898d-554fbc4b8b2b/_default#/EmbeddedTool;Component/embmainpage.xaml
app://e69a2877-59b8-43ed-898d-554fbc4b8b2b/_default#/EmbeddedTool;Component/fieldtrialpage.xaml
app://e69a2877-59b8-43ed-898d-554fbc4b8b2b/_default#/EmbeddedTool;Component/ft1xpage.xaml
app://e69a2877-59b8-43ed-898d-554fbc4b8b2b/_default#/EmbeddedTool;Component/ftactiveapnconnpage.xaml
app://e69a2877-59b8-43ed-898d-554fbc4b8b2b/_default#/EmbeddedTool;Component/ftbtpage.xaml
app://e69a2877-59b8-43ed-898d-554fbc4b8b2b/_default#/EmbeddedTool;Component/ftconfigpage.xaml
app://e69a2877-59b8-43ed-898d-554fbc4b8b2b/_default#/EmbeddedTool;Component/ftdatastatuspage.xaml
app://e69a2877-59b8-43ed-898d-554fbc4b8b2b/_default#/EmbeddedTool;Component/ftehrpdpage.xaml
app://e69a2877-59b8-43ed-898d-554fbc4b8b2b/_default#/EmbeddedTool;Component/ftgpspage.xaml
app://e69a2877-59b8-43ed-898d-554fbc4b8b2b/_default#/EmbeddedTool;Component/fthdrpage.xaml
app://e69a2877-59b8-43ed-898d-554fbc4b8b2b/_default#/EmbeddedTool;Component/ftltepage.xaml
app://e69a2877-59b8-43ed-898d-554fbc4b8b2b/_default#/EmbeddedTool;Component/ftmemorypage.xaml
app://e69a2877-59b8-43ed-898d-554fbc4b8b2b/_default#/RedirectionTool;Component/redirectionpage.xaml
app://e69a2877-59b8-43ed-898d-554fbc4b8b2b/_default#/ServiceToolLib;Component/homepage.xaml
app://e69a2877-59b8-43ed-898d-554fbc4b8b2b/_default#/ServiceToolLib;Component/view/checkspc.xaml
app://e69a2877-59b8-43ed-898d-554fbc4b8b2b/_default#/ServiceToolLib;Component/view/grouplists.xaml
app://e69a2877-59b8-43ed-898d-554fbc4b8b2b/_default#/ServiceToolLib;Component/view/itemedit.xaml
app://e69a2877-59b8-43ed-898d-554fbc4b8b2b/_default#/ServiceToolLib;Component/view/itemlists.xaml
app://e69a2877-59b8-43ed-898d-554fbc4b8b2b/_default#/ServiceToolLib;Component/view/lteavailablefile.xaml
app://e69a2877-59b8-43ed-898d-554fbc4b8b2b/_default#/ServiceToolLib;Component/view/pagelists.xaml
app://e69a2877-59b8-43ed-898d-554fbc4b8b2b/_default#/ServiceToolLib;Component/view/rwchoice.xaml
OMG!!!!!!!! so many xamls !
If you can get a Screen Shot of each xaml is more useful I think
None of them works. We need to add Dialercodes in the end.
tids2k said:
None of them works. We need to add Dialercodes in the end.
Click to expand...
Click to collapse
Oh i'm Really sorry . I have to buy an Ativ S to be a bit useful for other users but I have no money to buy
I'm again sorry I don't know what's going wrong in the Uris I provided :|
ngame said:
Oh i'm Really sorry . I have to buy an Ativ S to be a bit useful for other users but I have no money to buy
I'm again sorry I don't know what's going wrong in the Uris I provided :|
Click to expand...
Click to collapse
its alright mate.thanks for your help. I will try tomorrow.
did you check the xap's i posted in the other thread. I hope they will be useful. Thanks.
btw my phone came with Hong Kong firmware but I have installed the Australian firmware. Im glad atleast this was possible.
tids2k said:
its alright mate.thanks for your help. I will try tomorrow.
did you check the xap's i posted in the other thread. I hope they will be useful. Thanks.
btw my phone came with Hong Kong firmware but I have installed the Australian firmware. Im glad atleast this was possible.
Click to expand...
Click to collapse
@nGage were you able to install those apps on your phone ?
@nGage there is some good news i was able to run the strings which you posted. It was all about changing 'Component' -> 'component' and some other tweaks. But the .dll library refers to something else and hence the data is not fetchable. I will post the screenshots tomorrow. @W_O_L_F can this file 'HTC Diagnostics_Sprint be hacked in any way as I was able to install this on Nokia 1520 via Windows App Store -> SysPush ( via Fiddler i.e chainging the OEMID=HTC )
tids2k said:
@nGage there is some good news i was able to run the strings which you posted. It was all about changing 'Component' -> 'component' and some other tweaks. But the .dll library refers to something else and hence the data is not fetchable. I will post the screenshots tomorrow. @W_O_L_F can this file 'HTC Diagnostics_Sprint be hacked in any way as I was able to install this on Nokia 1520 via Windows App Store -> SysPush ( via Fiddler i.e chainging the OEMID=HTC )
Click to expand...
Click to collapse
Not for Nokia.
Be very careful with the HTC Sprint tool, since it has the ability to change NV values, even if it is commented out. (don't know why.) but it sure does.
hutchinsane_ said:
Be very careful with the HTC Sprint tool, since it has the ability to change NV values, even if it is commented out. (don't know why.) but it sure does.
Click to expand...
Click to collapse
thanks for the advice. But the app is pointless on Nokia phones as i have tried it and it doesn't work ... It can go to the menu's bit cannot get the values either it needs Interop or the dll linked is not for the device.
I need a way to search in StorageFiles with dynamically pattern, which comes from a TextBox. The directive "Windows.Storage.Search" doesnt exist in windows phone 8.1 runtime, as i saw. Now my question is, how can i do this in alternative way?
The only way to do it with WP 8.1 since Microsoft ALWAYS fails to implement the important things are to query using LINQ.
Ex:
Code:
var result = (await Windows.Storage.ApplicationData.Current.LocalFolder.GetFilesAsync(Windows.Storage.Search.CommonFileQuery.OrderByName)).
Where(x => x.Name.
Contains(x => txtBox.Text));
That's about all you can do pretty much. (Thanks Microsoft).
Thank you for the example. But it wont work for me, it shows me the following error(s):
Code:
A local variable named 'x' cannot be declared in this scope because it would give a different meaning to 'x', which is already used in a 'parent or current' scope to denote something else
and
Code:
Cannot convert lambda expression to type 'string' because it is not a delegate type
Thats really odd from Microsoft, that they havent implementet the search function like in WinRT (Windows Store App).
The first error is pretty simple. You already have the variable named "x" and it would be very bad if compiler didn't give you that error.
Change the name of the variable to something else that you don't use in that scope and it will work.
And for second problem, try this one:
Code:
private List<string> Result()
{
var result = ((List<Windows.Storage.Search.CommonFileQuery>)Windows.Storage.ApplicationData.Current.LocalFolder.GetFilesAsync(Windows.Storage.Search.CommonFileQuery.OrderByName)).Where(x => x.ToString().Contains(txtBox.Text));
return result as List<string>;
}
private async Task<List<string>> ResultAsync()
{
return await Task.Run(() => Result()).ConfigureAwait(continueOnCapturedContext: false);
}
You should call ResultAsync method and get the result in this way:
Code:
List<string> myList = ResultAsync().Result;
That's not going to work. You can't cast a StorageFile as a string.
To fix my code (simple lambda typo)
Code:
var result = (await Windows.Storage.ApplicationData.Current.LocalFolder.GetFilesAsync(Windows.Storage.Search.CommonFileQuery.OrderByName)).
Where(x => x.Name.
Contains(txtBox.Text));
if(result.Any())
{
// Do shtuff
}
Also, you should never access the .Result of an async task because you never know if it completed yet.
Ok, first error is done, but the second error is still here
Code:
Cannot convert lambda expression to type 'string' because it is not a delegate type
You are missing the point of the TAP (Task Async Pattern).
Both main thread and async method will be in execution in the same time. When the async method finish his work, main thread will stop and catch the result trough the Result property.
TAP is the recommended way of asynchronous programming in C#. The only thing with TAP is to use ConfigureAwait method in non-console type of apps to avoid deadlock.
Sooner or later you will get the result from TAP method. Nothing will get in the conflict with the main thread.
Oh wait, @andy123456 I updated my response. I forgot String.Contains ISNT a lambda .
@Tonchi91, I know all about the TAP. I've been using it since it was CTP. I've seen the awkward situations with threading in WP .
Now... if he did
Code:
List<string> myList;
ResultAsync().ContinueWith(t=> { myList = t.Result; });
I wouldn't be worried .
Ok the errors are gone, but the debugger show me the following exception:
Code:
Value does not fall within the expected range
Is this search method case-sensitive? I tried with an exact input in the TextBox.
Hmmm. Let's see your full code.
its actually only for testing, so i added your code to a button (asnyc) and will show the output in a textBlock.
Code:
private async void buttonTest_Click(object sender, RoutedEventArgs e)
{
//Result();
var result = (await Windows.Storage.KnownFolders.CameraRoll.GetFilesAsync(Windows.Storage.Search.CommonFileQuery.OrderByName)).
Where(x => x.Name.
Contains(textBox_test.Text));
if (result.Any())
{
// Do shtuff
textBlock_test.Text = result.ToString();
}
}
The error is coming from here
Code:
var result = (await Windows.Storage.KnownFolders.CameraRoll.GetFilesAsync(Windows.Storage.Search.CommonFileQuery.OrderByName))
andy123456 said:
its actually only for testing, so i added your code to a button (asnyc) and will show the output in a textBlock.
Code:
private async void buttonTest_Click(object sender, RoutedEventArgs e)
{
//Result();
var result = (await Windows.Storage.KnownFolders.CameraRoll.GetFilesAsync(Windows.Storage.Search.CommonFileQuery.OrderByName)).
Where(x => x.Name.
Contains(textBox_test.Text));
if (result.Any())
{
// Do shtuff
textBlock_test.Text = result.ToString();
}
}
The error is coming from here
Code:
var result = (await Windows.Storage.KnownFolders.CameraRoll.GetFilesAsync(Windows.Storage.Search.CommonFileQuery.OrderByName))
Click to expand...
Click to collapse
Oh Camera Roll.. You MIGHT need to have the capability to view the camera roll enabled. I forget what it's called, but you need a specific cap in order to view from there. Also, I would try to see if you can use a generic folder instead.
I would try Windows.Storage.ApplicationData.Current.LocalFolder.GetFilesAsync() as your method after the await just to test whether you can read correctly.
Yes but in wp8.1 runtime app, there arent caps anymore. The capability for access to the pictures is simply calles pictures library and is enabled. I have tested it as you said, but it gives me the same exception.
A quick tip: another way to do this is to use the Win32 C runtime API. You can, for example, use the FindFirst/NextFile functions (http://msdn.microsoft.com/en-us/library/windows/desktop/aa364418(v=vs.85).aspx) which support searches using wildcards (* and ? characters in the first parameter). These functions are wrapped in my NativeLibraries classes, but are also just publicly available for third0party developers to call from their own C++ DLLs.
Alternatively, you can use the .NET System.IO.Directory class, which has functions like EnumerateFiles(String path, String searchPattern). This is probably the better way to do it, actually.
Of course, if you want these operations to not block the current thread, you'll need to explicitly put them in their own thread or async function.
EDIT: This also assumes you have read access to the relevant directories. You application data directory works fine, for example (you can get its path from the relevant StorageFolder object). Other directories that can be accessed via WinRT functions may go through a broker function instead of being directly readable.
The point is, that i have an array with filenames. Now i need the StorageFile files which contains these filenames. My idea was to search for these files and return the files as StorageFile, so i can work with these. Or is there a simpler / another way?
http://msicc.net/?p=4182 <-- try this
Thank you, i have already done this and its working. But how can i compare the Files to read, with already read files and take only the not yet read files?
I'm making a project in Android Studio that requires the user to give permissions. The only code that I've found online and in YouTube tutorials is the following code:
public void onClick(View v) {
Intent i = new Intent();
i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
i.setData(Uri.parse("package:" + getPackageName()));
i.addFlags(Intent.FLaG_ACTIVITY_NEW_TASK);
startActivity(i);
}
It works however, I would like a direct code that will open permissions directly for my app. Not just the details. I know it's one click over but I would still like a direct code that will popup that permissions area at users request. I appreciate the help that I can get with this.