Search code examples
androidjsonandroid-intentgmailattachment

Android get data from gmail, attachment is json


What I want: Get data from json in gmail attachment.

Description: Open Gmail, click attachment which is json file. Json file handle data which I need to procesing.

In Manifest I declarated

<intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <data android:mimeType="application/json"/>
                <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

Next i use

Intent intent = getIntent();        
if(intent.getAction().equals(Intent.ACTION_VIEW)){ 
intent.getData <- I suppose from here i can get my infomation
        }

But intent.getData only return Uri, and I read someone i must use ContentResolver, InputStream and something else to for example write my data from json to string. If some can explain how it works on example I will appreciate it.


Solution

  • Ok i have it

    if (intent.getAction().equals(Intent.ACTION_VIEW)) {
                Toast.makeText(this, "work", Toast.LENGTH_SHORT).show();
                Uri data = intent.getData();
    //            ContentResolver contentResolver = getContentResolver();
                String text = getStringFromShare(data);
                Log.d("sasas", "onCreate: sometext");
            }
        }
    
        private String getStringFromShare(Uri data) {
            String text = null;
            try {
    
                ContentResolver cr = getApplicationContext().getContentResolver();
                InputStream is = cr.openInputStream(data);
                if (is != null) {
    
                    StringBuffer buf = new StringBuffer();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                    String str;
                    if (is != null) {
                        while ((str = reader.readLine()) != null) {
                            buf.append(str);
                        }
                    }
                    is.close();
                    text = buf.toString();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return text;
        }