FileNotFoundException when trying to screenshot - java

Below is my MainActivity and Manifest file. I am trying to implement a screenshot in my app which then gives the option to open the screenshot using other applications. When I click the button in the main activity nothing is happening. It keeps throwing java.io.FileNotFoundException like so
W/System.err: java.io.FileNotFoundException: /storage/emulated/0/ScreenShooter/2021-02-19_07:45:59.jpg: open failed: ENOENT (No such file or directory)
Is there a way to solve this?
package com.levirs.example.screenshooter;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
screenshoot();
}
});
}
private void screenshoot() {
Date date = new Date();
CharSequence now = android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", date);
String filename = Environment.getExternalStorageDirectory() + "/ScreenShooter/" + now + ".jpg";
View root = getWindow().getDecorView();
root.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(root.getDrawingCache());
root.setDrawingCacheEnabled(false);
File file = new File(filename);
file.getParentFile().mkdirs();
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "image/*");
startActivity(intent);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.levirs.example.screenshooter">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>

its seems like you are access the directory which not exist make sure its exist if you are using default screenshots folder then replace this line
Environment.getExternalStorageDirectory() + "/ScreenShooter/" + now + ".jpg";
to
Environment.getExternalStorageDirectory() + "/Pictures/Screenshots/" + now + ".jpg";
but this getExternalStorageDirectory is depricated now so use this one
getFilesDir()+ "/Pictures/Screenshots/" + now + ".jpg";

You're trying to instance a file on a path only via string which represents path+fileName.
Instead you should instance a new File with path separated from the fileName.
A similar problem

Related

Android Studio App crashes when i press the submit button to go to a 2nd activity

Firstly, I am pretty new to Android programming and I am trying to develop a simple app that shows a message, and when you press the button that's under the message, it sends you to a 2nd activity, which is a form. The app isn't linked to any database, I was just trying to develop a validation algorithm within the app, so the data that's written in the EditText's it's correct. Like the Name only with letters, etc. I created both activities, it worked to jump from the 1st one to the 2nd one after pressing the button, but that was before I added the validation algorithm. Now, with that implemented, whenever I press on the "Start!" button(1st activity-submit one), the apps just crashes.
The manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.myapplication">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme"
tools:ignore="GoogleAppIndexingWarning">
<activity
android:name=".Inregistrare"
android:exported="true"
android:theme="#style/AppTheme1" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
The 1st app MainActivity.java:
package com.example.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button submitButton = findViewById(R.id.submitButton);
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Inregistrare();
}
});
}
public void Inregistrare(){
Intent intent = new Intent(this,Inregistrare.class);
startActivity(intent);
}
}
The 2nd activity Inregistrare.java:
package com.example.myapplication;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class Inregistrare extends AppCompatActivity {
EditText nume, prenume, email, telefon;
TextView rezultat;
Button submit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inregistrare);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{ final String Nume = nume.getText().toString();
final String Prenume=prenume.getText().toString();
final String Email=email.getText().toString();
final String Telefon=telefon.getText().toString();
if(Nume.length()==0)
{
nume.requestFocus();
nume.setError("Campul nu poate fi lasat liber");
}
else if(!Nume.matches("[a-zA-Z ]+"))
{
nume.requestFocus();
nume.setError("Campul poate fi completat doar cu litere");
}
else if(Prenume.length()==0)
{
prenume.requestFocus();
prenume.setError("Campul nu poate fi lasat liber");
}
else if(!Prenume.matches("[a-zA-Z ]+")) {
prenume.requestFocus();
prenume.setError("Campul poate fi completat doar cu litere");
}
else if(Email.length()==0)
{
email.requestFocus();
email.setError("Campul nu poate fi lasat liber");
}
else if(!Email.matches("^[A-Z0-9._%+-]+#[A-Z0-9.-]+\\.[A-Z]{2,6}$"))
{
email.requestFocus();
email.setError("Campul poate fi completat doar cu litere");
}
else if(Telefon.length()==0 || Telefon.length()<10)
{
telefon.requestFocus();
telefon.setError("Campul nu poate fi lasat liber si trebuie sa aiba minim 10 cifre");
}
else if(!Telefon.matches("[0-9]+"))
{
telefon.requestFocus();
telefon.setError("Campul poate fi completat doar cu cifre");
}
else{
rezultat = findViewById(R.id.rezultat);
String date="Date corecte!";
rezultat.setText(date);
}
}
})
;}
}
I tried using another activity to check the switch and it works. The problem is somewhere in inregistrare.java (2nd activity) but i cant seem to find it. I didnt add the .xml's because i dont this that there's any problem. As i said i am pretty new to this, so please be kind and dont yell at me if i did a big mistake.
Thanks in advance!

Why is my ACTION_SEND working on API 25+ perfectly, but messes up on previous APIs?

So I have a Share button that will share an image and a body of text.
On Nougat (API 25) and Oreo (API 26), it works absolutely perfectly. But when it comes to a couple older version it doesn't work as expected.
Marshmallow (API 23): Inserts the image just fine but no body of text.
Lollipop (API 22): Crashes when you push the Share button with popup error "Unfortunately, Messaging has stopped." LOGCAT isn't showing me any errors when this happens.
Here is my share button code:
if (id == R.id.action_shareWine) {
Intent intentShare = new Intent(Intent.ACTION_SEND);
intentShare.putExtra(intentShare.EXTRA_STREAM, imageURI);
intentShare.setType("image/*");
intentShare.putExtra(Intent.EXTRA_TEXT, "body of text goes here");
if (intentShare.resolveActivity(getPackageManager()) != null) {
startActivity(intentShare);
}
return true;
}
Here is a picture to give a visual idea of whats going on:
Anyone have any ideas what could be going on here?
UPDATE 1
Here is the crash log for the Lollipop emulator:
FATAL EXCEPTION: Mms-1
Process: com.android.mms, PID: 7570
java.lang.IllegalStateException: Couldn't read row 0, col 0 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
Which I'm not sure why it is happening because the cursor is loading the image just fine in an ImageView in that same activity.
Call addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) on the ACTION_SEND Intent, to allow third parties the ability to read the content identified by the Uri.
Also, since the image would appear to be a JPEG (based on the file extension), the MIME type is image/jpeg, not image/* or image/png.
For More Details
working in Oreo and Marshmallow Version Read this
https://developer.android.com/reference/android/support/v4/content/FileProvider.html
Source Code
https://drive.google.com/open?id=1vfO43dMSt096CMp6nrOJNl3fJAf6MPwG
create xml folder inside providers_path.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.holostik.sharescreenshotexample">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA"></uses-permission>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.holostik.sharescreenshotexample.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths" />
</provider>
</application>
</manifest>
package com.holostik.sharescreenshotexample;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.holostik.sharescreenshotexample.share.ScreenshotType;
import com.holostik.sharescreenshotexample.share.ScreenshotUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
int n;
String photoPath;
LinearLayout rootContent;
ImageView iv_share;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rootContent = (LinearLayout) findViewById(R.id.rootContent);
iv_share = (ImageView) findViewById(R.id.iv_share);
iv_share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int permissionCheck = ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.CAMERA);
if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
Log.e("MainActivity ", "P granted");
takeScreenshot(ScreenshotType.FULL);
} else {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
}, 1);
}
} else {
Log.e("MainActivity", "Lower Than MarshMallow");
takeScreenshot(ScreenshotType.FULL);
}
}
});
}
/* Method which will take screenshot on Basis of Screenshot Type ENUM */
private void takeScreenshot(ScreenshotType screenshotType) {
Bitmap b = null;
switch (screenshotType) {
case FULL:
b = ScreenshotUtils.getScreenShot(rootContent);
break;
case CUSTOM:
//If Screenshot type is CUSTOM
break;
}
//If bitmap is not null
if (b != null) {
// showScreenShotImage(b);//show bitmap over imageview
Log.e("keshav", "bitmap is -- > " + b);
SaveImage(b);
shareScreenshot();
/* File saveFile = ScreenshotUtils.getMainDirectoryName(MainActivity.this);//get the path to save screenshot
File file = ScreenshotUtils.store(b, "screenshot" + screenshotType + ".jpg", saveFile);//save the screenshot to selected path
shareScreenshot(file);//finally share screenshot
Log.e("file Path", String.valueOf(file));
*/
} else
//If bitmap is null show toast message
Toast.makeText(MainActivity.this, R.string.screenshot_take_failed, Toast.LENGTH_SHORT).show();
}
private void SaveImage(Bitmap finalBitmap)
{
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
n = 10000;
n = generator.nextInt(n);
String fname = "Image-" + n + ".jpg";
File file = new File(myDir, fname);
if (file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/* TODO Show screenshot Bitmap */
// private void showScreenShotImage(Bitmap b) {
// imageView.setImageBitmap(b);
// }
private void shareScreenshot()
{
photoPath = Environment.getExternalStorageDirectory() + "/saved_images" + "/Image-" + n + ".jpg";
File F = new File(photoPath);
//Uri U = Uri.fromFile(F);
// Uri U = FileProvider.getUriForFile(getActivity(), getActivity().getApplicationContext().getPackageName() + ".my.package.name.provider", F);
// TODO your package name as well add .fileprovider
Uri U = FileProvider.getUriForFile(MainActivity.this.getApplicationContext(), "com.holostik.sharescreenshotexample.fileprovider", F);
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("image/png");
i.putExtra(Intent.EXTRA_STREAM, U);
startActivityForResult(Intent.createChooser(i, "Email:"), 1);
}
// TODO Share Screen SHOT End ..............
}

Java Android upload image to sever

I have a probleme with sending a photo to server. When I want to upload a photo a see in console:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
I did this :
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import org.apache.commons.codec.binary.Base64;
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.util.EntityUtils;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
public class MainActivity extends Activity {
Button btpic, btnup;
private Uri fileUri;
String picturePath;
Uri selectedImage;
Bitmap photo;
String ba1;
public static String URL = "Paste your URL here";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btpic = (Button) findViewById(R.id.cpic);
btpic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
clickpic();
}
});
btnup = (Button) findViewById(R.id.up);
btnup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
upload();
}
});
}
private void upload() {
// Image location URL
Log.e("path", "----------------" + picturePath);
// Image
Bitmap bm = BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] ba = bao.toByteArray();
ba1 = Base64.encodeBase64String(ba);
// Log.e("base64", "-----" + ba1);
// Upload image to server
new uploadToServer().execute();
}
private void clickpic() {
// Check Camera
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// Open default camera
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, 100);
} else {
Toast.makeText(getApplication(), "Camera not supported", Toast.LENGTH_LONG).show();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100 && resultCode == RESULT_OK) {
selectedImage = data.getData();
photo = (Bitmap) data.getExtras().get("data");
// Cursor to get image uri to display
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap photo = (Bitmap) data.getExtras().get("data");
ImageView imageView = (ImageView) findViewById(R.id.Imageprev);
imageView.setImageBitmap(photo);
}
}
public class uploadToServer extends AsyncTask<Void, Void, String> {
private ProgressDialog pd = new ProgressDialog(MainActivity.this);
protected void onPreExecute() {
super.onPreExecute();
pd.setMessage("Wait image uploading!");
pd.show();
}
#Override
protected String doInBackground(Void... params) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("base64", ba1));
nameValuePairs.add(new BasicNameValuePair("ImageName", System.currentTimeMillis() + ".jpg"));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String st = EntityUtils.toString(response.getEntity());
Log.v("log_tag", "In the try Loop" + st);
} catch (Exception e) {
Log.v("log_tag", "Error in http connection " + e.toString());
}
return "Success";
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
pd.hide();
pd.dismiss();
}
}
}
A log :
08:52:35.199 941-941/com.example.krzysiek.myapplication76 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.krzysiek.myapplication76, PID: 941
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.toString()' on a null object reference
at com.example.krzysiek.myapplication76.MainActivity.clickpic(MainActivity.java:90)
at com.example.krzysiek.myapplication76.MainActivity.access$000(MainActivity.java:34)
at com.example.krzysiek.myapplication76.MainActivity$1.onClick(MainActivity.java:52)
at android.view.View.performClick(View.java:5697)
at android.widget.TextView.performClick(TextView.java:10826)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
11-15 08:52:56.003 941-1089/com.example.krzysiek.myapplication76 W/System: ClassLoader referenced unknown path: /data/data/com.example.krzysiek.myapplication76/lib
11-15 08:54:47.258 941-950/com.example.krzysiek.myapplication76 W/art: Suspending all threads took: 12.657ms
My manifest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.krzysiek.myapplication76">
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
Bitmap bm = BitmapFactory.decodeFile(picturePath); returns null bitmap.
The reason would be need read external storage permission. Make sure you have supporting runtime permissions if you are using Android Operating System version which is above 5.0
Also make sure your picturePath represents a file which has URI scheme image.
Good luck there.
Emre

unable to create a file in SD card

I am very new into the android development.
In this project, I am trying to create a JSON objects and then want to write that JSON object into a file in SD card but I am getting the following exception:
W/System.err: java.io.FileNotFoundException: /storage/emulated/0/avinash1.json: open failed: EACCES (Permission denied)
Though I have even added the user-permission in the manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.raviteja.youexample">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
package com.example.raviteja.youexample;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JSONObject obj = new JSONObject();
try {
obj.put("age", new Integer(100));
obj.put("name", "Ravi");
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray list1 = new JSONArray();
JSONObject pnObj = new JSONObject();
try {
pnObj.put("num", "99009900");
pnObj.put("type", "mhgchmc");
list1.put(pnObj);
obj.put("phoneNumber", list1);
} catch (JSONException e) {
e.printStackTrace();
}
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath());
dir.mkdirs();
File file = new File(dir, "avinash1.json");
try {
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println(obj.toString());
pw.flush();
pw.close();
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You should maybe try to get the public directory with the command: getExternalStoragePublicDirectory(): android.os.Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
Although if you want to keep that info to yourself and not let any other apps touch it you should save it in your apps InteralStorage. Quick tutorial here: http://www.tutorialspoint.com/android/android_internal_storage.htm
Updating my Answer
use this method , it should work :
private void saveJson() {
File root = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
if(!root.exists())
{
root.mkdirs();
}
File file = new File(root, "avinash1.json");
try {
if (file.exists()) {file.delete ();}
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(json.toString());
bw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
but be careful , whenever you call this , your file will be overwritten with new value , for escaping that , you should make unique name for your file , like including current date and time to your file name ...

Modifying Proxy settings using android code with the connected wifi hotspot

I have created a hotspot from my windows7 machine and trying to write a code to connect my android phone to that hotspot.
I have been able to connect the phone.
Further I am trying to modify the proxy settings like IP and port for the connected hotspot using the code.
The phone is connecting to the hotspot but the code is unable to modify the proxy settings.
The code I have written is as follows:
Main_activity.java
I am connecting wifi hotspot created in vb.net and then connecting phone to that hotspot
` Package com.example.connect_avek;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.ProxyInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import static android.widget.Toast.LENGTH_LONG;
public class MainActivity extends Activity {
Button startbtn,stopbtn;
RelativeLayout background;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startbtn = (Button)findViewById(R.id.startbtn);
stopbtn = (Button)findViewById(R.id.stopbtn);
startbtn.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
public void onClick(View v) {
//start connection code
WifiManager wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);
WifiConfiguration wc = new WifiConfiguration();
wc.SSID = "\"" + "shashank" + "\""; // Please note the quotes. String should contain SSID in quotes
wc.preSharedKey = "\"" + "mummy#123" + "\"";
wc.status = WifiConfiguration.Status.ENABLED;
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
Log.d("connecting", wc.SSID + " " + wc.preSharedKey);
wifi.addNetwork(wc);
Log.d("after connecting", wc.SSID + " " + wc.preSharedKey);
List<WifiConfiguration> list = wifi.getConfiguredNetworks();
for (WifiConfiguration i : list) {
if (i.SSID != null && i.SSID.equals("\"" + "shashank" + "\"")) {
wifi.disconnect();
wifi.enableNetwork(i.networkId, true);
wifi.reconnect();
Log.d("re connecting", i.SSID + " " + wc.preSharedKey);
try {
Class proxyInfoClass = Class.forName("android.net.ProxyInfo");
Class[] setHttpProxyParams = new Class[1];
setHttpProxyParams[0] = proxyInfoClass;
Class wifiConfigClass = Class.forName("android.net.wifi.WifiConfiguration");
Method setHttpProxy = wifiConfigClass.getDeclaredMethod("setHttpProxy", setHttpProxyParams);
setHttpProxy.setAccessible(true);
//Method 1 to get the ENUM ProxySettings in IpConfiguration
Class ipConfigClass = Class.forName("android.net.IpConfiguration");
Field f = ipConfigClass.getField("proxySettings");
Class proxySettingsClass = f.getType();
//Method 2 to get the ENUM ProxySettings in IpConfiguration
//Note the $ between the class and ENUM
//Class proxySettingsClass = Class.forName("android.net.IpConfiguration$ProxySettings");
Class[] setProxySettingsParams = new Class[1];
setProxySettingsParams[0] = proxySettingsClass;
Method setProxySettings = wifiConfigClass.getDeclaredMethod("setProxySettings", setProxySettingsParams);
setProxySettings.setAccessible(true);
ProxyInfo pi = ProxyInfo.buildDirectProxy("192.168.137.1", 7777);
//Android 5 supports a PAC file
//ENUM value is "PAC"
//ProxyInfo pacInfo = ProxyInfo.buildPacProxy(Uri.parse("http://localhost/pac"));
//pass the new object to setHttpProxy
Object[] params_SetHttpProxy = new Object[1];
params_SetHttpProxy[0] = pi;
setHttpProxy.invoke(wc, params_SetHttpProxy);
//pass the enum to setProxySettings
Object[] params_setProxySettings = new Object[1];
params_setProxySettings[0] = Enum.valueOf((Class<Enum>) proxySettingsClass, "STATIC");
setProxySettings.invoke(wc, params_setProxySettings);
//save the settings
wifi.updateNetwork(wc);
wifi.disconnect();
wifi.reconnect();
} catch (Exception e) {
Log.v("wifiProxy", e.toString());
}
}
break;
}
}
});
stopbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//stop connection code
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(false);
}
});
}
} `
-----------------------------------------------------------------------------
**manifest.xml**
I have added the wifi permissions for the internet state and activity
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.connect_avek" >
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
----------------------------------------------------------------------------

Categories