【问题标题】:Failed to send image from one activity to another. Please see details无法将图像从一个活动发送到另一个活动。请查看详情
【发布时间】:2016-01-02 13:42:40
【问题描述】:

我正在从 facebook 获取用户的个人资料图片,我想将其发送到 ProfileActivity.java,以便它可以显示在用户个人资料中。

问题是图像没有从SignUpScreen.java 发送到ProfileActivity.java。虽然我可以将姓名和电子邮件从一个发送到另一个。

这是SignUpScreen.java 文件的代码:

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);
        }

    }
}

这是ProfileActivity.java 文件的代码:

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);
    }

}

请让我知道这里出了什么问题。

【问题讨论】:

  • 代码太多了。只需发布与问题相关的最低要求代码。
  • @ParagKadam 我修改了一些代码。请看一看。
  • 您是否已成功将 Facebook 中的图片提取到您的代码中?
  • 然后删除从facebook访问图像的代码。
  • @ParagKadam 请回答问题。我无法删除它,因为它用于另一段重要的代码。这会迷惑别人!!!

标签: java android facebook-graph-api facebook-android-sdk facebook-sdk-4.0


【解决方案1】:

在您的getUserDetailsFromFacebook() 方法中,您调用了new ProfilePicAsync().execute(userID) 来获取图像。但似乎在您获取图像之前,startActivity(profileIntent) 可能会被调用。 在致电startActivity(profileIntent) 之前,请先确保您已从 facebook 获取图片。

编辑

将此添加到您的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);

将此添加到您的ProfileActivity.java

byte[] byteArray = getIntent().getByteArrayExtra("user_pic");
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
mProfileImage.setImageBitmap(bmp);

【讨论】:

  • 不!我在那里放了一个处理程序,以便我可以在之前获取图像。它起作用了,我在触发意图之前获取了图像,但后来我也没有得到图像。
  • 此代码导致以下错误:Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference at com.abc.xyz.SignUpScreen$7.onCompleted(SignUpScreen.java:315)
  • 在写bmp.compress(Bitmap.CompressFormat.PNG, 100, stream)之前你有没有打电话给new ProfilePicAsync().execute(userID)
  • 在这种情况下,可能有两种可能性 - 1) 您无法从 facebook 检索图像(您可以通过在您的 SignupScreen 活动中获取 TextView 来确认这一点并显示图像在TextView)。 2)您的startActivity()new ProfilePicAsync().execute(userID) 完成之前被调用,因此bmp 具有null 值。
  • 您应该在您的 asyncTask 的 onPostExecute 中发布此代码 ByteArrayOutputStream stream = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.PNG, 100, stream); byte[] byteArray = stream.toByteArray(); profileIntent.putExtra("user_pic", byteArray); startActivity(profileIntent)
【解决方案2】:

这不是在同一应用程序中将图像从 Activity 传递到 Activity 的正确方法。您可以轻松地通过意图发送路径并将其加载到其他 Activity。

要将位图保存在Activity A 中,请使用

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();
    }
}

现在你有了FILENAME 全局字符串,可以从Activity B 访问。 只需将其加载到需要的位置即可。

BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(FILENAME, options);
mProfileImage.setImageBitmap(bitmap);

【讨论】:

  • 问题出在哪里兄弟? @HammadNasir
  • 我不知道问题出在哪里。我已成功从 facebook 获取图像,但我不知道为什么它没有从一个活动转移到另一个活动。
  • 图片保存后是否可以看到。首先将此图像保存到SD卡中。然后退出应用程序,看看它是否在 sdcard 中。如果它在那里,尝试在简单的活动中加载它。如果作品在您的应用程序中结合这两个任务。这应该很简单。
【解决方案3】:

它对我有用。

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    • 2012-07-20
    相关资源
    最近更新 更多