Download pictures using a service - java

I'm trying to download pictures in the background of an app using Service (not IntentSevice)
Somehow, my code doesn't work.
I set permissions for Internet and Storage in the Manifest.
I'm thankful for any comments or answers (:
Here's my code:
For the Service and then for the MainActivity
i have already tried different links or httpURLConnection instead of the normal URL connection but that doesnt't work either.
when I run the app, it always shows my "error" toast. it doesn't even get to the Input Stream.
public class Download extends Service {
public static final String URL = "url";
public static final String FILENAME = "name";
public static final String FILEPATH = "path";
public static final String RESULT = "result";
public static final String NOTIFICATION = "notification";
public ImageView imageView1 ;
#Override
public IBinder onBind(Intent arg0){
// TODO Auto-generated method stub
return null;
}
public void onCreate(){
super.onCreate();
Toast.makeText(this,"Service is created",Toast.LENGTH_LONG).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
String urlPath = intent.getStringExtra(FILEPATH);
String fileName = intent.getStringExtra(FILENAME);
int result = Activity.RESULT_CANCELED;
try {
Toast.makeText(this, "Service started", Toast.LENGTH_LONG).show();
final URL fileUrl = new URL(urlPath);
HttpURLConnection urlConnection = (HttpURLConnection) fileUrl.openConnection();
final InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
Toast.makeText(this, "connected", Toast.LENGTH_LONG).show();
//Toast.makeText(this, "connected", Toast.LENGTH_LONG).show();
File downloadordner = new File(Environment.getExternalStorageDirectory() + "/Pictures");
if (!downloadordner.exists()) {
downloadordner.mkdirs();
}
File downloadedfile = new File(downloadordner, "Bild1" + System.currentTimeMillis() + ".png");
OutputStream outputStream = new FileOutputStream(downloadedfile);
try {
byte[] buffer = new byte[1024];
int read;
while ((read = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, read);
}
result = Activity.RESULT_OK;
}finally{
outputStream.flush();
outputStream.close();
inputStream.close();
}
} catch (Exception e){
e.printStackTrace();
Toast.makeText(this,"Fehler",Toast.LENGTH_LONG).show();
}
publishResults(result);
return START_STICKY;
}
private void publishResults(int result){
Intent intent = new Intent(NOTIFICATION);
intent.putExtra(RESULT,result);
sendBroadcast(intent);
}
#Override
public void onDestroy(){
super.onDestroy();
Toast.makeText(this,"Service Stopped", Toast.LENGTH_LONG).show();
System.exit(0);
}
}
public class MainActivity extends AppCompatActivity {
Button btn1;
Button btn2;
ProgressBar progbar1;
public ImageView imageView1;
private TextView downloadStatus; //neu
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
downloadStatus = (TextView) findViewById(R.id.download_status);
progbar1 = (ProgressBar) findViewById(R.id.progbar1);
btn1 = (Button) findViewById(R.id.go);
btn2 = (Button) findViewById(R.id.kill);
imageView1 = (ImageView) findViewById(R.id.bild1);
btn1.setOnClickListener(onDownloadListener());
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopService(new Intent(getBaseContext(), Download.class));
System.exit(0);
}
});
}
private View.OnClickListener onDownloadListener(){
return new View.OnClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Download.class);
intent.putExtra(Download.FILENAME,"logo.png");
intent.putExtra(Download.FILEPATH,"https://de.wikipedia.org/wiki/Kleiner_Eisvogel#/media/File:Limenitis_camilla3.jpg");
startService(intent);
downloadStatus.setText("Downloading....");
Toast.makeText(MainActivity.this, "downloading", Toast.LENGTH_LONG).show();
}
};
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
#SuppressLint("SetTextI18n")
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if(bundle != null){
int resultCode = bundle.getInt(Download.RESULT);
if (resultCode == RESULT_OK){
Toast.makeText(MainActivity.this,"File downloaded",Toast.LENGTH_LONG).show();
downloadStatus.setText("Download completed");
}else{
Toast.makeText(MainActivity.this,"Error",Toast.LENGTH_LONG).show();
downloadStatus.setText("Download failed");
}
}
}
};
}

Service runs on the main thread so there is a network exception NO networking is allowed on the main thread.

Related

how to add instagram share to story button in my android app

Currently, I am getting this error: cannot find symbol
Bitmap bm = BitmapFactory.decodeResource(context.getResources(), R.drawable.bg);
I am trying to add Share to Instagram Story button. I had success with share to Whatsapp button. but stuck at this... does anyone can help me?
I want to add "Share to Instagram story" button on onExitButtonClicked
public class CustomDialogClass extends Dialog implements
android.view.View.OnClickListener {
public CustomDialogListener listener;
public Dialog d;
public Button yes, no, exit;
public CustomDialogClass(#NonNull Context context,
CustomDialogListener listener) {
super(context);
this.listener = listener ;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.custom_dialog);
yes = (Button) findViewById(R.id.btn_yes);
no = (Button) findViewById(R.id.btn_no);
exit = (Button) findViewById(R.id.btn_exit);
yes.setOnClickListener(this);
no.setOnClickListener(this);
exit.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_yes:
listener.onYesButtonClicked();
break;
case R.id.btn_no:
listener.onNoButtonClicked();
break;
case R.id.btn_exit:
listener.onExitButtonClicked();
break;
default:
break;
}
dismiss();
}
public interface CustomDialogListener {
public void onYesButtonClicked() ;
public void onNoButtonClicked() ;
public void onExitButtonClicked() ;
}
}
public void onBackPressed() {
CustomDialogClass cd = new CustomDialogClass(this, new CustomDialogClass.CustomDialogListener() {
#Override
public void onYesButtonClicked() {
try {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "sample text");
sendIntent.setType("text/plain");
sendIntent.setPackage("com.whatsapp");
startActivity(sendIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onNoButtonClicked() {
try {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, "URLyouWantToShare");
startActivity(Intent.createChooser(shareIntent, "Share..."));
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onExitButtonClicked() {
Bitmap bm = BitmapFactory.decodeResource(context.getResources(), R.drawable.bg);
File extStorageDirectory = context.getExternalCacheDir();
File stickerFile = new File(extStorageDirectory, "bg.png");
try {
FileOutputStream outStream = new FileOutputStream(stickerFile);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (IOException e) {
Log.e("TEST", e.getMessage());
}
Uri stickerUri = FileProvider.getUriForFile(this, "con.pixoid.upsend.fileprovider", stickerFile);
// Uri stickerUri = Uri.fromFile(stickerFile);
String linkUrl = "https://stackoverflow.com";
Intent intent = new Intent("com.instagram.share.ADD_TO_STORY");
intent.setType("image/*");
intent.putExtra("interactive_asset_uri", stickerUri);
intent.putExtra("content_url", linkUrl);
intent.putExtra("top_background_color", "#33FF33");
intent.putExtra("bottom_background_color", "#FF00FF");
grantUriPermission("com.instagram.android", stickerUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (getPackageManager().resolveActivity(intent, 0) != null) {
startActivityForResult(intent, 0);
}
}
});
cd.show();
}
Here's a Kotlin example:
private fun shareStory(){
val sticker = BitmapFactory.decodeResource(resources,
R.drawable.your_logo)
val savedImageURL: String = MediaStore.Images.Media.insertImage(
requireContext().contentResolver,
sticker,
"test_image",
"image_description"
)
val savedImageURI = Uri.parse(savedImageURL)
val storiesIntent = Intent("com.instagram.share.ADD_TO_STORY").apply {
type = "image/jpeg"
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
setPackage("com.instagram.android")
putExtra("interactive_asset_uri", savedImageURI)
putExtra("content_url", "something");
putExtra("top_background_color", "#33FF33");
putExtra("bottom_background_color", "#FF00FF")
}
requireContext().grantUriPermission("com.instagram.android", savedImageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION)
this.startActivity(storiesIntent)
}
Also here's a link for the official doc:
Instagram Stories

How can I save and get a image from my database

I take a picture and save the path into my SQLite database but it only saves 0 kb file and when I try to open it with the gallery it is not opening
this is my main activity:
static final int REQUEST_IMAGE_CAPTURE = 1;
static final int REQUEST_TAKE_PHOTO = 1;
Button btnTakePicture;
ImageView imageView;
String pathToFile;
Intent takePictureIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnTakePicture = findViewById(R.id.btnTakePicture);
final EditText txtname = (EditText) findViewById(R.id.txtname);
Button mcbutton = (Button) findViewById((R.id.mcbutton));
Button listbutton = (Button) findViewById((R.id.listbutton));
final DataBase db = new DataBase(getApplicationContext());
try {
db.onCreate(db.getWritableDatabase());
} catch (Exception ex) {
}
if (Build.VERSION.SDK_INT >= 23) {
requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 2);
}
btnTakePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
dispatchTakePictureIntent();
} catch (IOException e) {
e.printStackTrace();
}
}
});
mcbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String fname = txtname.getText().toString();
if (fname == null) {
Toast.makeText(getApplicationContext(), "Please enter something!!", Toast.LENGTH_SHORT).show();
return;
} else if (pathToFile == null) {
Toast.makeText(getApplicationContext(), "Please take a picture!!", Toast.LENGTH_SHORT).show();
return;
} else {
Model model = new Model(fname, pathToFile);
long id = db.ekleModel(model);
if (id > 0) {
Toast.makeText(getApplicationContext(), "Food Registration Perfect! ID = " + id, Toast.LENGTH_LONG).show();
txtname.setText("");
} else {
Toast.makeText(getApplicationContext(), "Please Enter a Food Name", Toast.LENGTH_LONG).show();
}
}
}
});
listbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), Random.class);
startActivity(intent);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
imageView.setImageBitmap(imageBitmap);
}
}
private void dispatchTakePictureIntent() throws IOException {
takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
File photoFile = null;
try {
photoFile = createPhotoFile();
} catch (IOException ex) {
}
}
}
private File createPhotoFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = new File(storageDir, imageFileName + ".jpg");
// Save a file: path for use with ACTION_VIEW intents
pathToFile = image.getAbsolutePath();
return image;
}
and this is my other activity where I get the problem,
everything is supposed to work but I don't know why bitmap decode returns null...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_random);
final EditText txtMulti = (EditText)findViewById(R.id.txtMulti);
final ImageView imageView = (ImageView)findViewById(R.id.imageView);
DataBase db = new DataBase(getApplicationContext());
List<Model> modellist = new ArrayList<Model>();
modellist = db.gelModelListesi();
StringBuilder sb = new StringBuilder();
for(Model _model: modellist){
String icerik = "";
icerik = "ID: "+_model.getId()+"Yemek Adı: "+_model.getFoodname()+ "\n\n";
File imgFile = new File(_model.getImagePath());
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getPath());
imageView.setImageBitmap(myBitmap);
}
sb.append(icerik);
}
txtMulti.setText(sb);
}

Failed to send image from one activity to another. Please see details

I'm fetching user's profile picture from facebook and I want to send it to ProfileActivity.java so that it can be displayed on user profile.
The problem is that the image is not getting sent from SignUpScreen.java to ProfileActivity.java. Though I am able to send name & email from one to another.
Here's SignUpScreen.java file's code:
public class SignUpScreen extends AppCompatActivity {
Button facebookLoginButton;
CircleImageView mProfileImage;
TextView mUsername, mEmailID;
Profile mFbProfile;
ParseUser user;
Bitmap bmp = null;
public String name, email, userID;
public static final List<String> mPermissions = new ArrayList<String>() {{
add("public_profile");
add("email");
}};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_sign_up_screen);
TextView textView = (TextView) findViewById(R.id.h);
Typeface typeface = Typeface.createFromAsset(getBaseContext().getAssets(), "fonts/Pac.ttf");
textView.setTypeface(typeface);
mProfileImage = (CircleImageView) findViewById(R.id.user_profile_image);
mUsername = (TextView) findViewById(R.id.userName);
mEmailID = (TextView) findViewById(R.id.aboutUser);
mFbProfile = Profile.getCurrentProfile();
//mUsername.setVisibility(View.INVISIBLE);
//mEmailID.setVisibility(View.INVISIBLE);
facebookLoginButton = (Button) findViewById(R.id.facebook_login_button);
facebookLoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ParseFacebookUtils.logInWithReadPermissionsInBackground(SignUpScreen.this, mPermissions, new LogInCallback() {
#Override
public void done(ParseUser user, ParseException err) {
if (user == null) {
Log.d("MyApp", "Uh oh. The user cancelled the Facebook login.");
} else if (user.isNew()) {
Log.d("MyApp", "User signed up and logged in through Facebook!");
getUserDetailsFromFacebook();
final Handler handler3 = new Handler();
handler3.postDelayed(new Runnable() {
#Override
public void run() {
saveNewUser();
}
}, 5000);
} else {
Log.d("MyApp", "User logged in through Facebook!");
}
}
});
}
});
}
public void saveNewUser() {
user = new ParseUser();
user.setUsername(name);
user.setEmail(email);
user.setPassword("hidden");
user.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Toast.makeText(SignUpScreen.this, "SignUp Succesful", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(SignUpScreen.this, "SignUp Unsuccesful", Toast.LENGTH_LONG).show();
Log.d("error when signingup", e.toString());
}
}
});
}
private void getUserDetailsFromFacebook() {
final GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
//Log.d("response", "response" + object.toString());
Intent profileIntent = new Intent(SignUpScreen.this, ProfileActivity.class);
Bundle b = new Bundle();
try {
name = response.getJSONObject().getString("name");
mUsername.setText(name);
email = response.getJSONObject().getString("email");
mEmailID.setText(email);
userID = response.getJSONObject().getString("id");
new ProfilePicAsync().execute(userID);
b.putString("userName", name);
b.putString("userEmail", email);
profileIntent.putExtras(b);
profileIntent.putExtra("user_pic", bmp);
startActivity(profileIntent);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "name, email, id");
request.setParameters(parameters);
request.executeAsync();
}
class ProfilePicAsync extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String imageURL;
String id = userID;
imageURL = "https://graph.facebook.com/"+ id +"/picture?type=large";
try {
bmp = BitmapFactory.decodeStream((InputStream)new URL(imageURL).getContent());
} catch (Exception e) {
e.printStackTrace();
Log.d("Loading picture failed", e.toString());
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
mProfileImage.setImageBitmap(bmp);
}
}
}
Here's ProfileActivity.java file's code:
public class ProfileActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Bundle bundle = getIntent().getExtras();
CircleImageView mProfileImage = (CircleImageView) findViewById(R.id.user_profile_image);
TextView mUsername = (TextView) findViewById(R.id.userName);
TextView mEmailID = (TextView) findViewById(R.id.aboutUser);
Bitmap bitmap = (Bitmap) getIntent().getParcelableExtra("user_pic");
mProfileImage.setImageBitmap(bitmap);
mUsername.setText(bundle.getString("userName"));
mEmailID.setText(bundle.getString("userEmail"));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
Please let me know what is going wrong here.
In your getUserDetailsFromFacebook() method you have called new ProfilePicAsync().execute(userID) to get the image. But it seems that before you could fetch the image ,startActivity(profileIntent) probably gets called.
First be sure that you have fetched the image from facebook before you call startActivity(profileIntent).
EDIT
Add this to your getUserDetailsFromFacebook() ,
b.putString("userName", name);
b.putString("userEmail", email);
profileIntent.putExtras(b);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
profileIntent.putExtra("user_pic", byteArray);
startActivity(profileIntent);
Add this to your ProfileActivity.java ,
byte[] byteArray = getIntent().getByteArrayExtra("user_pic");
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
mProfileImage.setImageBitmap(bmp);
This is not a right way to pass image from Activity to Activity within same application. You can easily send the path by intent and load it into other Activity.
To save a bitmap in Activity A, use
FileOutputStream out = null;
try {
out = new FileOutputStream(FILENAME); //FILENAME is your defined place to store image
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Now you have FILENAME global string which is accessible from Activity B.
Just load it where its needed.
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(FILENAME, options);
mProfileImage.setImageBitmap(bitmap);
it works for me.
OneActivity.java
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Intent intent = new Intent(StartPage.this, SecondActivity.class);
Toast.makeText(StartPage.this, "You have setted this wallpaper for Monday", Toast.LENGTH_LONG).show();
intent.putExtra("pic", byteArray);
//intent.putExtra("resourseInt", bm);
startActivity(intent);
SecondActivity.Java
byte[] byteArray;
Bitmap bmp,
byteArray = getIntent().getByteArrayExtra("pic");
bmp1 = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
myWallpaperManager.setBitmap(bmp);

Unexplained Android Intent Behaviour

im adding a camera scanning facility to a project of mine. Im using the following github https://github.com/jhansireddy/AndroidScannerDemo project
im attempting to call it from within an onclicklistener which is set within an adaptor i wrote
here is my onclicklistener
imgCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Intent intent = new Intent(context, ScanActivity.class);
// ((Activity) context).startActivity(intent);
Intent intent =new Intent(context, ScanAdaptor.class);
}
}
i want it to call a class i wrote which uses startactivityforresult :
public class ScanAdaptor extends Activity {
private Context context;
private static final int REQUEST_CODE = 99;
String ba1;
public String URL = "http:";
#Override
public void onCreate(Bundle savedInstanceState) {
int REQUEST_CODE = 99;
int preference = ScanConstants.OPEN_CAMERA;
Intent intent = new Intent(this, ScanActivity.class);
intent.putExtra(ScanConstants.OPEN_INTENT_PREFERENCE, preference);
startActivityForResult(intent, REQUEST_CODE);
context = this;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Uri uri = data.getExtras().getParcelable(ScanConstants.SCANNED_RESULT);
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
getContentResolver().delete(uri, null, null);
// scannedImageView.setImageBitmap(bitmap);
upload(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private Bitmap convertByteArrayToBitmap(byte[] data) {
return BitmapFactory.decodeByteArray(data, 0, data.length);
}
private void upload(Bitmap bm) {
// Image location URL
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] ba = bao.toByteArray();
int flag = 0;
ba1 = Base64.encodeToString(ba, flag);
Log.e("base64", "-----" + ba1);
// Upload image to server
new uploadToServer().execute();
}
public class uploadToServer extends AsyncTask<Void, Void, String> {
private ProgressDialog pd = new ProgressDialog(((Activity) context));
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();
Intent myIntent = new Intent(((Activity) context), MainActivity.class);
myIntent.putExtra("dir", "BS"); //Optional parameters
((Activity) context).startActivity(myIntent);
}
}
}
when this is the config nothing happens when you press the button.
its driving me mad, please help
Your onClick method doesn't launch the activity, it just creates the intent. Try this:
imgCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, ScanAdaptor.class);
((Activity) context).startActivity(intent);
}
}

how to get filename from uri for any file selected from gallery?

I am getting null value while using context for fragment on the line
selectedPath = ImageFilePath.getPath(mContext, uri);
public class DeviceDetailFragment extends Fragment implements ConnectionInfoListener {
protected static final int CHOOSE_FILE_RESULT_CODE = 20;
private View mContentView = null;
private WifiP2pDevice device;
private WifiP2pInfo info;
ProgressDialog progressDialog = null;
private Context mContext;
public static String filename;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
mContext = getActivity().getApplicationContext();
}
#SuppressLint("InflateParams")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mContentView = inflater.inflate(R.layout.device_detail, null);
mContentView.findViewById(R.id.btn_connect).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = device.deviceAddress;
config.wps.setup = WpsInfo.PBC;
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
progressDialog = ProgressDialog.show(getActivity(), "Press back to cancel",
"Connecting to :" + device.deviceAddress, true, true
);
((DeviceActionListener) getActivity()).connect(config);
}
});
mContentView.findViewById(R.id.btn_disconnect).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
((DeviceActionListener) getActivity()).disconnect();
}
});
mContentView.findViewById(R.id.btn_start_client).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, CHOOSE_FILE_RESULT_CODE);
}
});
return mContentView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Uri uri = data.getData();
if (resultCode == Activity.RESULT_OK)
{
if (requestCode == CHOOSE_FILE_RESULT_CODE)
{
String selectedPath;
selectedPath = ImageFilePath.getPath(mContext, uri);
filename = selectedPath.substring(selectedPath.lastIndexOf("/")+1);
}
}
TextView statusText = (TextView) mContentView.findViewById(R.id.status_text);
statusText.setText("Sending: " + uri);
Log.d(WiFiDirectActivity.TAG, "Intent----------- " + uri);
Intent serviceIntent = new Intent(getActivity(), FileTransferService.class);
serviceIntent.setAction(FileTransferService.ACTION_SEND_FILE);
serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, uri.toString());
serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_ADDRESS,
info.groupOwnerAddress.getHostAddress());
serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_PORT, 8988);
getActivity().startService(serviceIntent);
}
#Override
public void onConnectionInfoAvailable(final WifiP2pInfo info) {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
this.info = info;
this.getView().setVisibility(View.VISIBLE);
TextView view = (TextView) mContentView.findViewById(R.id.group_owner);
view.setText(getResources().getString(R.string.group_owner_text)
+ ((info.isGroupOwner == true) ? getResources().getString(R.string.yes)
: getResources().getString(R.string.no)));
view = (TextView) mContentView.findViewById(R.id.device_info);
view.setText("Group Owner IP - " + info.groupOwnerAddress.getHostAddress());
if (info.groupFormed && info.isGroupOwner) {
new FileServerAsyncTask(getActivity(), mContentView.findViewById(R.id.status_text))
.execute();
} else if (info.groupFormed) {
mContentView.findViewById(R.id.btn_start_client).setVisibility(View.VISIBLE);
((TextView) mContentView.findViewById(R.id.status_text)).setText(getResources()
.getString(R.string.client_text));
}
mContentView.findViewById(R.id.btn_connect).setVisibility(View.GONE);
}
public void showDetails(WifiP2pDevice device) {
this.device = device;
this.getView().setVisibility(View.VISIBLE);
TextView view = (TextView) mContentView.findViewById(R.id.device_address);
view.setText(device.deviceAddress);
view = (TextView) mContentView.findViewById(R.id.device_info);
view.setText(device.toString());
}
public void resetViews() {
mContentView.findViewById(R.id.btn_connect).setVisibility(View.VISIBLE);
TextView view = (TextView) mContentView.findViewById(R.id.device_address);
view.setText(R.string.empty);
view = (TextView) mContentView.findViewById(R.id.device_info);
view.setText(R.string.empty);
view = (TextView) mContentView.findViewById(R.id.group_owner);
view.setText(R.string.empty);
view = (TextView) mContentView.findViewById(R.id.status_text);
view.setText(R.string.empty);
mContentView.findViewById(R.id.btn_start_client).setVisibility(View.GONE);
this.getView().setVisibility(View.GONE);
}
public static class FileServerAsyncTask extends AsyncTask<Void, Void, String> {
private Context context;
private TextView statusText;
public FileServerAsyncTask(Context context, View statusText) {
this.context = context;
this.statusText = (TextView) statusText;
}
#Override
protected String doInBackground(Void... params) {
try {
ServerSocket serverSocket = new ServerSocket(8988);
Log.d(WiFiDirectActivity.TAG, "Server: Socket opened");
Socket client = serverSocket.accept();
Log.d(WiFiDirectActivity.TAG, "Server: connection done");
final File f = new File(Environment.getExternalStorageDirectory() + "/"
+ context.getPackageName() + "/" + filename);
File dirs = new File(f.getParent());
if (!dirs.exists())
dirs.mkdirs();
f.createNewFile();
Log.d(WiFiDirectActivity.TAG, "server: copying files " + f.toString());
InputStream inputstream = client.getInputStream();
copyFile(inputstream, new FileOutputStream(f));
serverSocket.close();
return f.getAbsolutePath();
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
return null;
}
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
statusText.setText("File copied - " + result);
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + result), "*/*");
context.startActivity(intent);
}
}
#Override
protected void onPreExecute() {
statusText.setText("Opening a server socket");
}
}
public static boolean copyFile(InputStream inputStream, OutputStream out) {
byte buf[] = new byte[1024];
int len;
long startTime=System.currentTimeMillis();
try {
while ((len = inputStream.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.close();
inputStream.close();
long endTime=System.currentTimeMillis()-startTime;
Log.v("","Time taken to transfer all bytes is : "+endTime);
} catch (IOException e) {
Log.d(WiFiDirectActivity.TAG, e.toString());
return false;
}
return true;
}
}
here is the code for the FileNamePath class
public class FileTransferService extends IntentService {
private static final int SOCKET_TIMEOUT = 5000;
public static final String ACTION_SEND_FILE = "com.example.android.wifidirect.SEND_FILE";
public static final String EXTRAS_FILE_PATH = "file_url";
public static final String EXTRAS_GROUP_OWNER_ADDRESS = "go_host";
public static final String EXTRAS_GROUP_OWNER_PORT = "go_port";
public FileTransferService(String name) {
super(name);
}
public FileTransferService() {
super("FileTransferService");
}
/*
* (non-Javadoc)
* #see android.app.IntentService#onHandleIntent(android.content.Intent)
*/
#Override
protected void onHandleIntent(Intent intent) {
Context context = getApplicationContext();
if (intent.getAction().equals(ACTION_SEND_FILE)) {
String fileUri = intent.getExtras().getString(EXTRAS_FILE_PATH);
String host = intent.getExtras().getString(EXTRAS_GROUP_OWNER_ADDRESS);
Socket socket = new Socket();
int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);
try {
Log.d(WiFiDirectActivity.TAG, "Opening client socket - ");
socket.bind(null);
socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);
Log.d(WiFiDirectActivity.TAG, "Client socket - " + socket.isConnected());
OutputStream stream = socket.getOutputStream();
ContentResolver cr = context.getContentResolver();
InputStream is = null;
try {
is = cr.openInputStream(Uri.parse(fileUri));
} catch (FileNotFoundException e) {
Log.d(WiFiDirectActivity.TAG, e.toString());
}
DeviceDetailFragment.copyFile(is, stream);
Log.d(WiFiDirectActivity.TAG, "Client: Data written");
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
} finally {
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
} catch (IOException e) {
// Give up
e.printStackTrace();
}
}
}
}
}
}
}
i am not able to get the filename and only getting null.

Categories