Retrieve the saved WiFi passwords from Android devices - android

I am developing an Android application in which I need to show the saved WiFi passwords in the mobile or tablet. Like for example, if my mobile is connected to any network that n/w password is saved in my mobile. I want to get it.

Unless you are rooted, I don't know of any way to do it. If you are rooted, or are willing to root your Galaxy for those nice guy points, you should be able to use a file manager (ASTRO, Root Browser, etc.) to find it.
Use the file manager to locate your data/misc/file folder, then look for wpa_supplicant.conf, or I assume it could be wep_supplicant.conf if his/her network is using WEP instead of WPA. Open the .conf file using a text editor (which is probably built into your file manager application, if not, add that to your shopping list). You should be able to read the password in plain text at that point.

Your Comments helped me to some extent to find out the solution to my question. Especially #Namik Kalavadia I am talking about you Thanks for that.
Finally here is the solution.
public class MainActivity extends Activity {
File file;
public StringBuffer ab;
public File savefile;
public InputStream in = null;
public String filename = "wpa_supplicant.conf";
public File ot_path;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplicationContext();
ot_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Log.d("aaa", ""+ot_path.toString());
}
public void path(View v){
getPath();
}
private void getPath(){
file = Environment.getRootDirectory();
String ext = ".conf";
File list[] = file.listFiles();
ab = new StringBuffer();
if(list!=null){
fileNameSearch(list);
}
}
public void fileNameSearch(File list[]){
if(list!=null){
for(int f = 0;f<list.length;f++){
ab.append(list[f].getName()+"\n");
File fi = list[f];
String path = fi.getPath();
if(fi.isDirectory()){
fileNameSearch(fi.listFiles());
}
else if(path.endsWith(".conf")){
if(path.contains(filename)){
try{
File fileForParse = copyFile(path,ot_path);
in = new FileInputStream(fileForParse);
getStringFromInputStream(in);
Log.d("aaa", "conf I got it"+path);
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}
else{
Log.d("aaa", "List is null in method");
}
}
private File copyFile(String inputPath, File outputPath) {
InputStream input = null;
OutputStream out = null;
try {
if (!outputPath.exists())
{
outputPath.mkdirs();
}
savefile = new File(outputPath,filename);
if (!savefile.exists()) {
savefile.createNewFile();
File f = new File(inputPath);
Log.d("aaa",""+f.length());
input = new FileInputStream(inputPath);
out = new FileOutputStream(savefile);
byte[] buffer = new byte[1024];
int read;
while ((read = input.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
Log.d("aaa",""+savefile.length());
input.close();
input = null;
out.flush();
out.close();
out = null;
}
} catch (FileNotFoundException fnfe1) {
Log.e("aaa", fnfe1.getMessage());
return null;
}
catch (Exception e) {
Log.e("aaa", e.getMessage());
return null;
}
return savefile;
}
#SuppressWarnings("deprecation")
private String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
if(line.contains("ssid")||line.contains("psk")){
sb.append(line+"\n");
}
if(line.contains("}")){
sb.append("-----------------\n");
}
AlertDialog ad = new AlertDialog.Builder(MainActivity.this).create();
ad.setTitle("Lis of WiFi Passwords Saved in your Mobile");
ad.setMessage(sb);
ad.setButton("OK",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
finish();
}
});
ad.show();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
}

It is not possible as far as I know . It will be a security problem if sdk tools allows to do so .

Retrieving saved Wifi password programatically is not possible due to security issue.If you root your phone you may able to get it,but that too in an encrypted form.

Related

compiling cpp files on runtime Android Studio

I am making a compiling app with my custom made a language. This app will change the custom made language code automatically to a CPP code. So all I need to do is compile the CPP code on runtime.
I got stuck compiling a CPP file in my app.
I have already checked out using dexmaker and image-playground, but I had problems with the Gradle-build. They are somewhat old projects and I'm not really sure how to use it so I passed that one.
So I am trying to use the command line tool with the android studio. I have saved my CPP file and can use it I think. Below includes my file i/o code. This is my code.
Code:
public class Code_cpp extends AppCompatActivity {
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.code_cpp);
TextView textView = (TextView) findViewById(R.id.view);
textView.setMovementMethod(new ScrollingMovementMethod());
context = this;
}
public void savebutton(View v) {
final EditText edit = (EditText) findViewById(R.id.edit_text);
TextView textView = (TextView) findViewById(R.id.view);
Log.v("EditText", edit.getText().toString());
String messageString = edit.getText().toString();
writeToFile(messageString,context);
Toast.makeText(getApplicationContext(), "saved", Toast.LENGTH_LONG).show();
}
private void writeToFile(String data,Context context) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.cpp", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
Log.e("Success", "File write Success ");
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
public void loadbutton(View v){
String msg = readFromFile(context);
TextView textView = (TextView) findViewById(R.id.view);
textView.setText(msg);
}
private String readFromFile(Context context) {
String ret = "";
try {
InputStream inputStream = context.openFileInput("config.cpp");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString).append("\n");
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
public void run(View v){
try {
Process process = Runtime.getRuntime().exec("g++ config.cpp;./a.out");
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
int read;
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
while ((read = reader.read(buffer)) > 0) {
output.append(buffer, 0, read);
}
reader.close();
// Waits for the command to finish.
process.waitFor();
//return output.toString();
String result=output.toString();
TextView textView = (TextView) findViewById(R.id.view);
textView.setText(result);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
I get an error when I click the run button
Caused by: java.io.IOException: Cannot run program "g++": error=13, Permission denied
I don't want to root my phone because I don't want to use this app just on my phone but with other phones too when I download it. Do I have to try another way to compile this? Why do I get permission denied errors?

Read data of type double from a text file in Android

I want to read data of type double saved in a .txt file from a previously specified folder. I've implemented the following code to read data then put them in an array of type double named savg1. when I run my application , it going to crash and the application stop. I tried to debug the application step by step and found that crash happens when the code reaches to savg1[i] = Double.parseDouble(str).
public void filereader()
{
InputStream is=this.getResources().openRawResource(R.raw.nums);
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String str=null;
int i=0;
try
{
if (is !=null)
{
str=br.readLine();
while (str != null) {
savg1[i] = Double.parseDouble(str);
i++;
str=br.readLine();
}
is.close();
br.close();
}
} catch (IOException e)
{
e.printStackTrace();
}
}
I am a newbie in Android developing so excuse me about my elementary question. Can anybody guide me how I can solve this problem?
Use following code to read data from your file. Note that in this method each number should be in a separate line:
double svg1[] = new double[10];
try {
InputStream is = getResources().openRawResource(R.raw.data);
DataInputStream dis = new DataInputStream(is);
while (dis.available() > 0) {
String test = dis.readLine();
double a = Double.parseDouble(test);
}
}catch (Exception e){
e.printStackTrace();
}
You can use file scanner for reading double type data saved in a text file as bellow:
public void fileReader(){
Scanner scan;
File file = new File("resources\\scannertester\\data.txt");
int idx = 0;
try {
scan = new Scanner(file);
while(scan.hasNextDouble())
savg1[idx++] = scan.nextDouble();
} catch (FileNotFoundException error) {
error.printStackTrace();
}
scan.close();
}

Data stored in file is erased after exiting the app

I'm using this code to save data to file and read data from the file:
public static void save(FileIO files) {
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(
files.writeFile(".save")));
for (int i = 0; i < 20; i++) {
out.write(Integer.toString(scores[i]));
out.write("\n");
}
} catch (IOException e) {
} finally {
try {
if (out != null)
out.close();
} catch (IOException e) {
}
}
}
public static void load(FileIO files) {
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(
files.readFile(".save")));
for (int i = 0; i < 20; i++) {
scores[i] = Integer.parseInt(in.readLine());
}
} catch (IOException e) {
} catch (NumberFormatException e) {
} finally {
try {
if (in != null)
in.close();
} catch (IOException e) {
}
}
}
FileIO.java
package com.avoidblocks.avoidblocks.framework;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.SharedPreferences;
public interface FileIO {
public InputStream readFile(String file) throws IOException;
public OutputStream writeFile(String file) throws IOException;
public InputStream readAsset(String file) throws IOException;
public SharedPreferences getSharedPref();
}
I'm calling save(FileIO files) and load(FileIO files) multiple times in an app and it works fine while I'm in an app, but when I exit the app and start the app again, all data is gone.
Does anyone know how to create that data remains saved even when I exit the app, so that I could restore the data when I start the app again?
Also, is this the right way to save data if I want that saved data is only visible to my app and that after uninstall, all saved data is erased?
EDIT-EDIT-EDIT:
ok its your FileIO files variable that looks like it is wrong,
what are you using to get that variable?
should be
context.openFileOutput(".save", Context.MODE_PRIVATE)
for save and
context.openFileInput(".save")
for load
and it should be FileOutputStream for save and FileInputStream for read instead of FileIO.
and when adding it to the stream just pass that in.
so in your code you should create the BufferedWriter like this:
out = new BufferedWriter(new OutputStreamWriter(
context.openFileOutput(".save", Context.MODE_PRIVATE)));
and create BufferedReader like this:
in = new BufferedReader(new InputStreamReader(
context.openFileInput(".save")));
==================EDIT: my testing code=================
Ok, I created an activity and made the following two methods and declared an array of ints:
public static int scores[] = {11,12,13,14,15};
public static void save(Context context) {
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(
context.openFileOutput(".saveingTest", Context.MODE_PRIVATE)));
for (int i = 0; i < scores.length; i++) {
out.write(Integer.toString(scores[i]));
out.write("\n");
}
} catch (IOException e) {
} finally {
try {
if (out != null)
out.close();
} catch (IOException e) {
}
}
}
public static void load(Context context) {
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(
context.openFileInput(".saveingTest")));
for (int i = 0; i < scores.length; i++) {
Log.d("testingApp", "test: " + Integer.parseInt(in.readLine()));
// scores[i] = Integer.parseInt(in.readLine());
}
} catch (IOException e) {
} catch (NumberFormatException e) {
} finally {
try {
if (in != null)
in.close();
} catch (IOException e) {
}
}
}
in my onCreate I have the following two lines of code:
save(this);
load(this);
to test I did the following:
commented out load in onCreate, ran the app, than I removed the comment on load and commented out save in onCreate and i changed the numbers in the scores variable(this is unnecessary but i did it anyway) and ran the app, the result was the int values in scores from the first time the app was run, inside the android log viewer window on eclipse. you can also have buttons that trigger save and load instead if you don't want to comment and run.
try it yourself, it should work, and make sure you are doing the same thing in your actual android app, if it still dose not work you are doing something else wrong and its not an issue with saving the file.

Android, downloading and using a .db file

(I'm deeply sorry for my poor english)
For a school project, i have to realize an Android Application. It uses an intern SQLite Database which is a copy from a website MySQL database. (The android application is a search engine for an Electrical Engineering database)
Since it has to be independant from the website (offline), i have to create an update option.
For this purpose, i've made a special DownloadHelper class :
#SuppressLint("SdCardPath")
public final class DownloadHelper extends AsyncTask<Void,Void,Void>
{
Context context;
File cheminBdd = new File("/data/data/com.example.btc_pe/databases/basesqlite.db");
public DownloadHelper(Context ctxt)
{ this.context = ctxt; }
#Override
protected Void doInBackground(Void... params)
{
// TODO Auto-generated method stub
try
{
downloadDatabase(cheminBdd);
//copyServerDatabase(this.context);
}
catch (Exception ex)
{
Log.e("BTC","Failed to download database !",ex);
}
return null;
}
private static void downloadDatabase(File destFile) throws IOException
{
URLConnection ucon;
InputStream is = null;
OutputStream os = null;
try
{
Log.d("BTC","start DL");
URL url = new URL("adresse" + "basesqlite.db");
ucon = url.openConnection();
Log.d("BTC","Connection open");
is = ucon.getInputStream();
Log.d("BTC","Stream In got");
os = new FileOutputStream(destFile);
Log.d("BTC","Debut copy()");
copy(is,os);
Log.d("BTC","end DL");
}
finally
{
if (os != null) try { os.close(); } catch (Exception ex) { Log.e("BTC","Failed to gracefully close output stream",ex); }
if (is != null) try { is.close(); } catch (Exception ex) { Log.e("BTC","Failed to gracefully close input stream",ex); }
}
}
public static int copy(InputStream input, OutputStream output) throws IOException
{
byte[] buffer = new byte[8192];
int count = 0;
int n = 0;
while (-1 != (n = input.read(buffer)))
{
output.write(buffer, 0, n);
count += n;
}
output.flush();
return count;
}
#SuppressLint("SdCardPath")
private void copyServerDatabase(Context context)
{
BtcDb db = new BtcDb(context,"clean.db",null,0);
// by calling this line an empty database will be created into the default system path
// of this app - we will then overwrite this with the database from the server
db.getReadableDatabase();
db.close();
OutputStream os = null;
InputStream is = null;
try {
// Log.d("BTC", "Copying DB from server version into app");
is = context.openFileInput("basesqlite.db");
os = new FileOutputStream("/data/data/com.example.btc_pe/databases/");
copyFile(os, is);
}
catch (Exception e)
{
Log.e("BTC", "Server Database was not found - did it download correctly?", e);
}
finally
{
try
{
//Close the streams
if(os != null)
{
os.close();
}
if(is != null)
{
is.close();
}
}
catch (IOException e)
{
Log.e("BTC", "failed to close databases");
}
}
Log.d("BTC", "Done Copying DB from server");
}
private static void copyFile(OutputStream os, InputStream is) throws IOException
{
byte[] buffer = new byte[1024];
int length;
while((length = is.read(buffer))>0)
{
os.write(buffer, 0, length);
}
os.flush();
}
}
I call the update by an Actionbar button, using DownloadHelper.execute() method from an instanciated object.
Then i get an exception after passed the "is = ucon.getInputStream();", i get this LogCat :
http://www.dump-it.fr/btcpng/7865ef3fef44de25fd62f01dad23d02d.png.html
Of course, i checked this file on the server, my URL, my Android Devices. Nothing to do.
If somebody could give me a hand, i'm getting lost :/

Save mobile number in a file android

I have developed an android app that enable the user to register by his/her mobile phone number. I want my app to save the phone number so that next time the user open the app, there will be no need to enter the phone number again, analogous to Whatsapp..
Here is my code, but it doesn't work and I still have to enter the phone number each time I open the app, besides, after adding this code to my app, the app became so heavy and slow.
if (android.os.Build.VERSION.SDK_INT > 9)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
try {
TelephonyManager tMgr = (TelephonyManager) getApplicationContext()
.getSystemService(Context.TELEPHONY_SERVICE);
mPhoneNumber = tMgr.getLine1Number().toString();
} catch (Exception e) {
String EE = e.getMessage();
}
if (mPhoneNumber == null) {
try {
fOut = openFileOutput("textfile.txt", MODE_WORLD_READABLE);
fIn = openFileInput("textfile.txt");
InputStreamReader isr = new InputStreamReader(fIn);
char[] inputBuffer = new char[50];
if (isr.read(inputBuffer) == 0) {
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Warrning");
alert.setMessage("Please Set Your Phone number");
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
mPhoneNumber = input.getText().toString();
try {
fIn = openFileInput("textfile.txt");
InputStreamReader isr = new InputStreamReader(fIn);
char[] inputBuffer = new char[50];
if (isr.read(inputBuffer) == 0) {
OutputStreamWriter osw = new OutputStreamWriter(fOut);
// ---write the string to the file---
osw.write(mPhoneNumber);
osw.flush();
osw.close();
// ---display file saved message---
Toast.makeText(getBaseContext(),
"Phone number saved successfully!",
Toast.LENGTH_SHORT).show();
// ---clears the EditText---
input.setText("");
} else {
int charRead;
while ((charRead = isr.read(inputBuffer)) > 0) {
// ---convert the chars to a String---
String readString = String.copyValueOf(inputBuffer,
0, charRead);
mPhoneNumber = readString;
inputBuffer = new char[50];
}
// ---set the EditText to the text that has been
// read---
Toast.makeText(getBaseContext(),
"Phone number read successfully!",
Toast.LENGTH_SHORT).show();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
int UserServiceId = CallLogin(mPhoneNumber);
if (UserServiceId > 0) {
Intent Service = new Intent(MainScreeen.this,
RecipeService.class);
Service.putExtra("UserId", UserServiceId);
startService(Service);
} else {
Intent Reg = new Intent(MainScreeen.this,
Regsteration.class);
Reg.putExtra("PhoneNumber", mPhoneNumber);
startActivity(Reg);
}
}
});
alert.show();
} else {
int UserServiceId = CallLogin(mPhoneNumber);
if (UserServiceId > 0) {
Intent Service = new Intent(MainScreeen.this,
RecipeService.class);
Service.putExtra("UserId", UserServiceId);
startService(Service);
} else {
Intent Reg = new Intent(MainScreeen.this, Regsteration.class);
Reg.putExtra("PhoneNumber", mPhoneNumber);
startActivity(Reg);
}
}
Please help me to figure it out !!
Well, in this block of code:
if (mPhoneNumber == null) {
try {
fOut = openFileOutput("textfile.txt", MODE_WORLD_READABLE);
fIn = openFileInput("textfile.txt");
you open the file for output, which will destroy anything that you've already written to it. Later, when you try to read from this file, it is all too late.
Also, you've got way too much code here. Don't reinvent the wheel. You don't need to read files a character at a time. If all you want to do is to write a string into the file and later read it back out again, use DataInputStream and DataOutputStream and you can read/write strings directly using readUTF() and writeUTF(). Here's a simple example to r ead the file:
DataInputStream in = new DataInputStream(openFileInput("textfile.txt"));
String contents = in.readUTF();
to write the file use:
DataOuputStream out = new DataOutputStream(openFileOutput("textfile.txt", 0));
out.writeUTF(phoneNumber);
Obviously you need to add the try/catch blocks and deal with exceptions and make sure you close the streams in a finally block, but you will end up with a lot less code if you do it like this.
To help you I give you my activity example in order to read and write data in a file:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class StoreDataActivity extends Activity {
private static final String TAG = "ExerciceActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
writeFileOnDisk("toto.txt", "Bienvenue chez Android");
String content = readFileOnDisk("toto.txt");
Log.v(TAG, "content=" + content);
}
private void writeFileOnDisk(String filename, String data) {
try {
FileOutputStream fos = openFileOutput(filename, this.MODE_PRIVATE);
fos.write(data.getBytes());
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String readFileOnDisk(String filename) {
int inChar;
StringBuffer buffer = new StringBuffer();
try {
FileInputStream fis = this.openFileInput(filename);
while ((inChar = fis.read()) != -1) {
buffer.append((char) inChar);
}
fis.close();
String content = buffer.toString();
return content;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

Categories

Resources