post image with text to linkedIn from android app - java

I want to post image from SD Card with text to linkedIn from my android app.
I could share text but image is not sharing.
I tried with following code:
share.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String share = et.getText().toString();
if (null != share && !share.equalsIgnoreCase("")) {
OAuthConsumer consumer = new CommonsHttpOAuthConsumer(Config.LINKEDIN_CONSUMER_KEY, Config.LINKEDIN_CONSUMER_SECRET);
consumer.setTokenWithSecret(accessToken.getToken(), accessToken.getTokenSecret());
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost("https://api.linkedin.com/v1/people/~/shares");
try {
consumer.sign(post);
} catch (OAuthMessageSignerException e) {
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
e.printStackTrace();
} catch (OAuthCommunicationException e) {
e.printStackTrace();
} // here need the consumer for sign in for post the share
post.setHeader("content-type", "text/XML");
byte[] data = null;
try {
ileInputStream fis = new FileInputStream(imgUrl1);
Bitmap bi = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream()
bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
Log.d("onCreate", "debug error e = " + e.toString());
}
String myEntity = "<share><comment>"+ text +"</comment> <content><submitted-image-url>data</submitted-image-url></content><visibility><code>anyone</code></visibility></share>";
try {
post.setEntity(new StringEntity(myEntity));
org.apache.http.HttpResponse response = httpclient.execute(post);
Toast.makeText(LinkedInSampleActivity.this,
"Shared sucessfully", Toast.LENGTH_SHORT).show();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else {
Toast.makeText(LinkedInSampleActivity.this,
"Please enter the text to share",
Toast.LENGTH_SHORT).show();
}
}
});
}

In linkedIn you can't share the local images.
For that you need to store the images in server and get the url of that image, now you can post the image to linkedIn...
This may help you...

Related

Why I have Permission denied on a file located in /data/user_de/

I want to get the attached content of MMS like Image or Video/audio.
First I make this
static void getMmsContent(Context context, ArrayList<Mms> mmsArrayList) {
try {
for (Mms unMms : mmsArrayList) {
ContentResolver contentResolver = context.getContentResolver();
Uri uri = Uri.parse("content://mms/part");
String selection = Telephony.Mms.Part.MSG_ID + "=" + unMms.getId();
Cursor query = contentResolver.query(uri, null, selection, null, null);
if (query != null && query.moveToFirst()) {
do {
String name = query.getString(query.getColumnIndex("name"));
String type = query.getString(query.getColumnIndex("ct"));
String txt = query.getString(query.getColumnIndex(Telephony.Mms.Part.TEXT));
String data = query.getString(query.getColumnIndex(Telephony.Mms.Part._DATA));
if (!type.equals("application/smil")) {
String[] dataMms = {name, type, txt, data};
getContent(context, dataMms, unMms);
}
} while (query.moveToNext());
}
if (query != null) {
query.close();
}
}
} catch (Exception e) {
Log.d("Exception", e.toString());
}
}
This line give me the path to the location of the attached content.
String data = query.getString(query.getColumnIndex(Telephony.Mms.Part._DATA));
/data/user_de/0/com.android.providers.telephony/app_parts/PART_1555841710097_Screenshot_20190421-121445_Chrome1.jpg
So now i want to transform the image to a Bitmap to add it to a zip file.
static private void getContent(Context context, String[] dataMms, Mms unMms){
if (dataMms[1].equals("text/plain")) {
unMms.setCorps(dataMms[2]);
} else {
if ("image/jpeg".equals(dataMms[1]) || "image/bmp".equals(dataMms[1]) ||
"image/gif".equals(dataMms[1]) || "image/jpg".equals(dataMms[1]) ||
"image/png".equals(dataMms[1])) {
unMms.setTypeContenu(dataMms[1]);
Bitmap bitmap = null;
InputStream is = null;
try {
File source = new File(dataMms[3]);
is = new FileInputStream(source);
bitmap = BitmapFactory.decodeStream(is);
} catch (IOException e) {
Log.d("Exception", e.toString());
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
Log.d("Exception", e.toString());
}
}
}
if (bitmap != null) {
File file = new File(context.getApplicationInfo().dataDir + "/files/", dataMms[0]);
OutputStream Fout = null;
try {
Fout = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, Fout);
Fout.flush();
Fout.close();
} catch (FileNotFoundException e) {
Log.d("Exception", e.toString());
} catch (IOException e) {
Log.d("Exception", e.toString());
}
}
}
}
}
But my code Throw a Exception on new FileInputStream(source);
I got this
D/Exception: java.io.FileNotFoundException: /data/user_de/0/com.android.providers.telephony/app_parts/PART_1547316880687_Resized_20190112_191438_9422.jpeg (Permission denied)
I have the permissions and i have require the user permission.
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
So i change my code after the comment of CommonsWare to this :
static private void getContent(Context context, String[] dataMms, Mms unMms) {
if (dataMms[1].equals("text/plain")) {
unMms.setCorps(dataMms[2]);
} else {
if ("image/jpeg".equals(dataMms[1]) || "image/bmp".equals(dataMms[1]) ||
"image/gif".equals(dataMms[1]) || "image/jpg".equals(dataMms[1]) ||
"image/png".equals(dataMms[1])) {
unMms.setTypeContenu(dataMms[1]);
Uri partURI = Uri.parse("content://mms/part/" + dataMms[4]);
InputStream is = null;
Bitmap bitmap = null;
try {
is = context.getContentResolver().openInputStream(partURI);
bitmap = BitmapFactory.decodeStream(is);
} catch (IOException e) {
Log.d("Exception", e.toString());
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
Log.d("Exception", e.toString());
}
}
}
if (bitmap != null) {
File file = new File(context.getApplicationInfo().dataDir + "/files/", dataMms[0]);
OutputStream Fout = null;
try {
file.createNewFile();
Fout = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, Fout);
Fout.flush();
Fout.close();
} catch (FileNotFoundException e) {
Log.d("Exception", e.toString());
} catch (IOException e) {
Log.d("Exception", e.toString());
}
}
}
}
}
The tricky part is this :
Uri partURI = Uri.parse("content://mms/part/" + dataMms[4]);
my dataMms[4] is the id of the MMS Part, I get it from this line I put on getMmsContent() :
String id = query.getString(query.getColumnIndex("_id"));
This column give me the id of the part.
But there is no mention about this column in Android Developer documentation : https://developer.android.com/reference/android/provider/Telephony.Mms.Part.html
So I listed the columns with this code in getMmsContent() and I found it :
for (int i = 0; i < query.getColumnCount(); i++) {
Log.i("Column", query.getColumnName(i));
}
Now It's working !

Snackbar not showing instantly

i'm trying to save a image when an ImageView is clicked. Because the saving takes some time i want to have some sort of indicator, that the app is working. I tried to use Snackbar for that. My code looks something like this:
File image = new File(directory, "image.png");
if(!image.exists()){
Snackbar bar = Snackbar.make(getActivity().findViewById(R.id.some_layout), "snackText", Snackbar.LENGTH_INDEFINITE);
bar.show();
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
bar.dismiss();
}
All that is inside the public void onClick(View view) of that ImageView.
The problem is, that the Snackbar only shows after the image is saved. I tried to force update the UI with invalidate() and tried it without starting a new Thread with the same result.
Any ideas are greatly appreciated!
Don't use snackbar here edit your code like this:
if(!image.exists()){
final ProgressDialog progressDialog =ProgressDialog.show(this, "","Please Wait...", true);
Thread t = new Thread(new Runnable() {
#Override
public void run() {
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog.dismiss();
}
});
}
});
t.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

how to decrypt(AES) locally stored encrypted file in storage

i am new to android ,i building activity clicking submit button get data from five edittext as json and covert to AES encryption and store it on local when i refresh or else restart the activity i want fetch the file decrypt and auto populated to 5 edit text ... encryption works fine for me but decryption wont... help me
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1 = (EditText)findViewById(R.id.editText1);
e2 = (EditText)findViewById(R.id.editText2);
e3 = (EditText)findViewById(R.id.editText3);
e4 = (EditText)findViewById(R.id.editText4);
e5 = (EditText)findViewById(R.id.editText5);
final JSONObject obj = new JSONObject();
sub = (Button)findViewById(R.id.button);
final File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "Outer_Folder");
file.mkdir(); // store and fetch file from storage...
f1 = new File(file,"null"+".txt");
f2 = new File(fileD,"null"+".txt");
try {
SecureRandom srm = SecureRandom.getInstance("SHA1PRNG");
srm.setSeed("no one can read".getBytes());
KeyGenerator kg = KeyGenerator.getInstance("AES");
kg.init(128,srm);
sec = kg.generateKey();
bb1 = sec.getEncoded();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
if (f1.exists()){
File file3 = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "Outer_Folder");
f4 = new File(file3,"null"+".txt");
int size = (int)f4.length();
contents = new byte[size];
try {
bufferedInputStream = new BufferedInputStream(new FileInputStream(f4));
try {
bufferedInputStream.read(contents);
bufferedInputStream.close();
String dd = new String(contents);
SecretKeySpec sdf = new SecretKeySpec(bb1,"AES");
Cipher cv = Cipher.getInstance("AES");
cv.init(Cipher.DECRYPT_MODE,sdf);
decodefile = cv.doFinal(dd.getBytes()); // aes decryption not working
String ggg = new String(decodefile);
Toast.makeText(getApplicationContext(),ggg,Toast.LENGTH_SHORT).show();
JSONObject jsonObj = new JSONObject(ggg);
v1=jsonObj.getString("one");
v2=jsonObj.getString("two"); // when enter the activity json filled by decryped file
v3=jsonObj.getString("three");
v4=jsonObj.getString("four");
v5=jsonObj.getString("five");
e1.setText(v1);
e2.setText(v2);
e3.setText(v3);
e4.setText(v4);
e5.setText(v5);
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
catch (BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} }else {
Toast.makeText(getApplicationContext(),"con't read",Toast.LENGTH_LONG).show();
} sub.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
public void onClick(View v) {
s1=e1.getText().toString();
s2=e2.getText().toString();
s3=e3.getText().toString();
s4=e4.getText().toString();
s5=e5.getText().toString();
try {
obj.put("one", s1);
obj.put("two", s2);
obj.put("three", s3); //converting json
obj.put("four", s4);
obj.put("five", s5);
if (f1.exists()){ //
f1.delete();
}
vv = obj.toString();
new execute();
try {
SecretKeySpec sksep = new SecretKeySpec(bb1,"AES");
Cipher cp = Cipher.getInstance("AES");
cp.init(Cipher.ENCRYPT_MODE,sksep);
encobyte = cp.doFinal(vv.getBytes()); // aes encryption - working
FileOutputStream uu = null;
uu = new FileOutputStream(f1);
uu.write(encobyte);
oo = new String(encobyte);
Toast.makeText(getApplicationContext(),oo,Toast.LENGTH_LONG).show();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) { //
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace(); //
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
This is probably a serialization/deserialization error, although it is difficult to know without any errors or other information.
Try using hexadecimal or Base64 encoding on the encobyte array before serializing that data to persistent storage. Perform the corresponding decoding operation on the retrieved data dd before decrypting it.

How to change the background color for layouts using configuration file in android

I want to change the background color for layouts dynamically for the first time only, using configuration file in android that file should be in assets folder,it can be xml file or anything.
please help me.
If you set an ID to your layout as follows :
<LinearLayout android:id="#+id/myLayout">
<LinearLayout/>
Then you can set your backGround in onCreate like this:
myLayout= findViewById(R.id.myLayout);
myLayout.setBackgroundColor(Color.BLUE);
1.use color for int value.
in the assets file config.txt, you can input color for int value like this. for example this value is Color.RED
4294901760
2.use this code in your appliaction
String config = "config.txt";
InputStream is = null;
try {
is = getAssets().open(config);
DataInputStream dis = new DataInputStream(is);
String color = dis.readUTF();
ColorDrawable drawable = new ColorDrawable(Integer.parseInt(color));
//use drawable
//for example
new TextView(this).setBackgroundColor(Integer.parseInt(color));
new TextView(this).setBackgroundDrawable(drawable);
} catch (IOException e) {
e.printStackTrace();
} finally {
if(is != null)
{
try {
is.close();
} catch (IOException e) {
}
}
}
3.you can use reflect, but in the config file, write the color name from values/colors.xml.
String config = "config.txt";
InputStream is = null;
try {
is = getAssets().open(config);
DataInputStream dis = new DataInputStream(is);
String color = dis.readUTF();
try {
Field field = R.color.class.getDeclaredField(color);
field.setAccessible(true);
Integer id = (Integer) field.get(null);
ColorDrawable drawable = new ColorDrawable(getResources().getColor(id));
// use drawable
// for example
new TextView(this).setBackgroundColor(getResources().getColor(id));
new TextView(this).setBackgroundDrawable(drawable);
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
}

how to get binary format values from video file? [duplicate]

I want to upload a video in web server. I got the service which to i want to pass a file in binary format how can i do this ?
I have tried to convert the video file into binary format with the help of base64..?
public class binaryformat extends Activity {
private String strAttachmentCoded;
Button b1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
File file = new File("/mnt/sdcard/C:/Program Files (x86)/Wowza Media Systems/Wowza Media Server 3.1.2/content/sample.mp4");
FileInputStream objFileIS = null;
try
{
objFileIS = new FileInputStream(file);
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
ByteArrayOutputStream objByteArrayOS = new ByteArrayOutputStream();
byte[] byteBufferString = new byte[1024];
try
{
for (int readNum; (readNum = objFileIS.read(byteBufferString)) != -1;)
{
objByteArrayOS.write(byteBufferString, 0, readNum);
System.out.println("read " + readNum + " bytes,");
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] byteBinaryData = Base64.encode((objByteArrayOS.toByteArray()), Base64.DEFAULT);
strAttachmentCoded = new String(byteBinaryData);
}
});
}
}
I have experienced in my 3 application that it is good if use XML to send the IMAGE or VIDEO over server.
Sending IMAGE or VIDEO in the form of base64 String in the XML is best if you want to upload a IMAGE or VIDEO in ANDROID.
public static String uploadMultiplePhoto(String url, String xmlString) {
String responseString = "";
try {
//instantiates httpclient to make request
DefaultHttpClient httpclient = new DefaultHttpClient();
//url with the post data
HttpPost request = new HttpPost(url);
//convert parameters into JSON object
//JSONObject holder = new JSONObject(jsonObjString);
//passes the results to a string builder/entity
StringEntity se = new StringEntity(xmlString);
//sets the post request as the resulting string
request.setEntity(se);
//sets a request header so the page receving the request
//will know what to do with it
request.setHeader("Accept", "application/xml");
/*request.setHeader("Content-type", "application/xml");*/
//Handles what is returned from the page
ResponseHandler<String> responseHandler = new BasicResponseHandler();
responseString = httpclient.execute(request, responseHandler);
} catch (Exception exception) {
exception.printStackTrace();
}
return responseString;
}

Categories

Resources