将gridView中的Image(来自Json)传递给新的Activity

时间:2017-03-10 15:38:17

标签: android gridview

我的应用中有一个包含图像的gridView。图像通过网络从json加载。我希望当用户点击gridView中的任何图像时,新活动将打开容器,用户点击该图像。图像从json中定义的链接加载。我试过但没有得到理想的结果。

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;

import com.dragedy.dream.adapter.MyArrayAdapter;
import com.dragedy.dream.model.MyDataModel;
import com.dragedy.dream.parser.JSONParser;
import com.dragedy.dream.utils.InternetConnection;
import com.dragedy.dream.utils.Keys;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class memechoose extends AppCompatActivity {


    private GridView gridView;
    private ArrayList<MyDataModel> list;
    private MyArrayAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_memechoose);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        /**
         * Array List for Binding Data from JSON to this List
         */
        list = new ArrayList<>();
        /**
         * Binding that List to Adapter
         */
        adapter = new MyArrayAdapter(this, list);

        /**
         * Getting List and Setting List Adapter
         */
        gridView = (GridView) findViewById(R.id.gridView);
        gridView.setAdapter(adapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


                Intent i= new Intent(memechoose.this, MemeEditorActivity.class);
                i.putExtra("image_path", list.get(position).getImage());
               startActivity(i);

            }
        });

        /**
         * Just to know onClick and Printing Hello Toast in Center.
         */


        if (InternetConnection.checkConnection(getApplicationContext())) {
            new GetDataTask().execute();
        }

    }

    /**
     * Creating Get Data Task for Getting Data From Web
     */
    class GetDataTask extends AsyncTask<Void, Void, Void> {

        ProgressDialog dialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            /**
             * Progress Dialog for User Interaction
             */
            dialog = new ProgressDialog(memechoose.this);
            dialog.setTitle("Hey Wait Please...");
            dialog.setMessage("I am getting your JSON");
            dialog.show();
        }

        @Nullable
        @Override
        protected Void doInBackground(Void... params) {

            /**
             * Getting JSON Object from Web Using okHttp
             */
            JSONObject jsonObject = JSONParser.getDataFromWeb();

            try {
                /**
                 * Check Whether Its NULL???
                 */
                if (jsonObject != null) {
                    /**
                     * Check Length...
                     */
                    if(jsonObject.length() > 0) {
                        /**
                         * Getting Array named "contacts" From MAIN Json Object
                         */
                        JSONArray array = jsonObject.getJSONArray(Keys.KEY_MEME);

                        /**
                         * Check Length of Array...
                         */
                        int lenArray = array.length();
                        if(lenArray > 0) {
                            for(int jIndex = 0; jIndex < lenArray; jIndex++) {

                                /**
                                 * Creating Every time New Object
                                 * and
                                 * Adding into List
                                 */
                                MyDataModel model = new MyDataModel();

                                /**
                                 * Getting Inner Object from contacts array...
                                 * and
                                 * From that We will get Name of that Contact
                                 *
                                 */
                                JSONObject innerObject = array.getJSONObject(jIndex);

                                String image = innerObject.getString(Keys.KEY_MEME_PIC);

                                /**
                                 * Getting Object from Object "phone"
                                 */



                                model.setImage(image);

                                /**
                                 * Adding name and phone concatenation in List...
                                 */
                                list.add(model);
                            }
                        }
                    }
                } else {

                }
            } catch (JSONException je) {
                Log.i(JSONParser.TAG, "" + je.getLocalizedMessage());
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            dialog.dismiss();
            /**
             * Checking if List size if more than zero then
             * Update ListView
             */
            if(list.size() > 0) {
                adapter.notifyDataSetChanged();
            } //else {
               // Snackbar.make(findViewById(R.id.parentLayout), "No Data Found", Snackbar.LENGTH_LONG).show();
           // }
        }
    }

}

以及我想要显示图像的活动如下:

public class MemeEditorActivity extends AppCompatActivity {


    private Toolbar toolbar;
    private MemeEditorActivity  selfRef;
    private SharedPreferences   setting;
    private LinearLayout        linlaHeaderProgress;
    private float               memeEditorLayoutWidth;
    private float               memeEditorLayoutHeight;
    private LinearLayout        tutorial;
    private LinearLayout        memeEditorLayout;
    private MemeEditorView      memeEditorView;
    private ImageView           forwardButtonImageView;
    private Bitmap              memeBitmap;
    private File                cacheImage_forPassing;
    private File                myDir;
    private String              dataDir;
    private boolean             firsttimes;
    private boolean             tutorialPreference;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_meme_editor);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(false);

        selfRef = this;

        // Transparent bar on android 4.4 or above
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.KITKAT)
        {
            Window window = getWindow();
            // Translucent status bar
            window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            // Translucent navigation bar
            window.setFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }

        // Initialize progress bar
        linlaHeaderProgress = (LinearLayout)findViewById(R.id.linlaHeaderProgress);
        linlaHeaderProgress.bringToFront();

        // Initialize tutorial
        setting = PreferenceManager
                .getDefaultSharedPreferences(MemeEditorActivity.this);
        SharedPreferences prefre = getSharedPreferences("Meme_Pref", Context.MODE_PRIVATE);
        firsttimes = prefre.getBoolean("Meme_Pref", true);
        tutorialPreference = setting.getBoolean("Tutor_Preference", false);
        SharedPreferences.Editor firstTimeEditor = prefre.edit();

        // See if tutorial is needed to be shown
        tutorial = (LinearLayout)findViewById(R.id.meme_editor_tutorial);
        tutorial.setEnabled(false);
        tutorial.setOnClickListener(new View.OnClickListener()
        {
            @ Override
            public void onClick(View view)
            {
                tutorial.setVisibility(View.GONE);
                tutorial.setEnabled(false);
            }
        });
        if(firsttimes)
        {
            tutorial.setVisibility(View.VISIBLE);
            tutorial.bringToFront();
            tutorial.setEnabled(true);
            firstTimeEditor.putBoolean("Meme_Pref", false);
            firstTimeEditor.commit();

        }
        else if(tutorialPreference)
        {
            tutorial.setVisibility(View.VISIBLE);
            tutorial.bringToFront();
            tutorial.setEnabled(true);
            tutorialPreference = setting.getBoolean("Tutor_Preference", false);
        }
        else
        {
            tutorial.setVisibility(View.GONE);
            tutorial.setEnabled(false);
        }

        // Get the data directory for the app
        PackageManager m = getPackageManager();
        dataDir = getPackageName();
        try
        {
            PackageInfo p = m.getPackageInfo(dataDir, 0);
            dataDir = p.applicationInfo.dataDir;
            myDir = new File(dataDir+"/cache");
            if(!myDir.exists())
                myDir.mkdirs();
            if(myDir.setWritable(true))
                Log.i("meme", "myDir is writable");
            else
                Log.i("meme", "myDir is not writable");
        }catch(PackageManager.NameNotFoundException e)
        {
            Log.w("yourtag", "Error Package name not found ", e);
        }

        // Get the intent and get the image path to be the meme image
        Intent shareIntent = getIntent();
        String imagePath = shareIntent.getStringExtra("image_path");






        // Create the SandboxView
        setting = PreferenceManager
                .getDefaultSharedPreferences(MemeEditorActivity.this);
        // final int memeSize = Integer.valueOf(setting.getString("image_size","720"));
        final int memeSize = setting.getInt("image_size", 720);
        Log.i("meme", "memeSize = "+memeSize);
        memeEditorLayout = (LinearLayout)findViewById(R.id.memeEditorLayout);
        memeEditorLayout.setGravity(Gravity.CENTER);
        try
        {
            Log.i("imagePath", imagePath);
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            memeEditorView = new MemeEditorView(this, bitmap);
            memeEditorView.setLayoutParams(new ViewGroup.LayoutParams(memeSize, memeSize));

            // Scale the sand box and add it into the layout
            ViewTreeObserver viewTreeObserver = memeEditorLayout
                    .getViewTreeObserver();
            // For getting the width and height of a dynamic layout during
            // onCreate
            viewTreeObserver
                    .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener()
                    {
                        @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
                        @ Override
                        public void onGlobalLayout()
                        {
                            memeEditorLayout.getViewTreeObserver()
                                    .removeGlobalOnLayoutListener(this);
                            memeEditorLayoutWidth = memeEditorLayout.getHeight();
                            memeEditorLayoutHeight = memeEditorLayout.getWidth();
                            float scalingFactor = memeEditorLayoutWidth/(float)memeSize;
                            Log.i("memeEditorLayoutWidth", Float.toString(memeEditorLayoutWidth));
                            Log.i("ScaleFactor", Float.toString(scalingFactor));
                            memeEditorView.setScaleX(scalingFactor);
                            memeEditorView.setScaleY(scalingFactor);
                        }
                    });
            memeEditorLayout.addView(memeEditorView);

            // Set save button on click method
            forwardButtonImageView = (ImageView)findViewById(R.id.forwardButtonImage);
            forwardButtonImageView.setOnClickListener(new View.OnClickListener()
            {
                @ Override
                public void onClick(View arg0)
                {
                    forwardButtonImageView.setEnabled(false);
                    Forward forward = new Forward();
                    forward.execute();
                }
            });
        }catch(OutOfMemoryError e)
        {
            Toast.makeText(selfRef, "Your device is out of memory.", Toast.LENGTH_LONG).show();
            finish();
        }catch(Exception e)
        {
            Log.i("Meme Editor Activity", e.toString());
            Toast.makeText(selfRef, "Ops, something went wrong.", Toast.LENGTH_LONG).show();
            finish();
        }
    }


    // Delete a files
    private void deleteFile(File file)
    {
        if(file!=null)
        {
            Log.i("deleteFile", file.toString()+((file.exists())?" is Exist.":"is not exist!!!!"));

            // Check if the file exist
            if(file.exists())
                // Clear the file inside if it is a directory
                if(file.isDirectory())
                {
                    String[] children = file.list();
                    for(int i = 0;i<children.length;i++)
                    {
                        File f = new File(file, children[i]);
                        if(f.delete())
                            Log.i("deleteFile", f.getAbsolutePath()+" is deleted....");
                        else
                            Log.i("deleteFile", f.getAbsolutePath()+" is not deleted!!!!");
                    }
                }
        }
    }


    @ Override
    protected void onPause()
    {
        // Hide the progress bar
        linlaHeaderProgress.setVisibility(View.GONE);
        forwardButtonImageView.setEnabled(true);

        super.onPause();
    }


    @ Override
    protected void onResume()
    {
        super.onResume();
        memeEditorView.setEnabled(true);
        memeEditorView.resume();
    }


    @ Override
    protected void onDestroy()
    {
        // Try to delete cache if possible
       // deleteFile(myDir);
       // bp_release();
        //memeEditorView.destroyDrawingCache();
        super.onDestroy();
    }


    @ Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.meme_editor, menu);
        return true;
    }


    @ Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        switch(item.getItemId())
        {
            case R.id.reset_sandbox:
                memeEditorView.reset();
                return true;
            case R.id.action_settings:
                Intent intent = new Intent(selfRef, MainActivity.class);
                startActivity(intent);
                return true;
            case android.R.id.home:
                // When the action bar icon on the top right is clicked, finish this
                // activity
                this.finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }


    // save image to a specific places
    private void saveImage()
    {
        // Create the file path and file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String fname = timeStamp+".png";
        cacheImage_forPassing = new File(myDir, fname);

        // Remove duplicates
        if(cacheImage_forPassing.exists())
            cacheImage_forPassing.delete();

        // Try save the bitmap
        try
        {
            FileOutputStream out = new FileOutputStream(cacheImage_forPassing);
            memeBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            out.flush();
            out.close();
            Log.i("memeCacheLocation", cacheImage_forPassing.toString());

        }catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    // Async task for onClick
    class Forward extends AsyncTask<Object,Object,Object>
    {
        // Before forwarding
        @ Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            linlaHeaderProgress.setVisibility(View.VISIBLE);
            linlaHeaderProgress.bringToFront();
            memeEditorView.pause();
            memeEditorView.invalidate();
        }


        // Forwarding
        @ Override
        protected String doInBackground(Object ... arg0)
        {
            Intent forward = new Intent(selfRef, MainActivity.class);
            memeEditorView.setDrawingCacheEnabled(true);
            memeEditorView.buildDrawingCache();
            memeBitmap = Bitmap.createBitmap(memeEditorView.getDrawingCache());
            saveImage();
            forward.putExtra("cs4295.memcreator.memeImageCache",
                    cacheImage_forPassing.getPath());
            startActivity(forward);
            memeEditorView.setDrawingCacheEnabled(false);
            return "DONE";
        }


        // After forwarding
        @ Override
        protected void onPostExecute(Object result)
        {
            linlaHeaderProgress.setVisibility(View.GONE);
            super.onPostExecute(result);
        }
    }


    // Clear the Bitmap from memory
    private void bp_release()
    {
        if(memeBitmap!=null&&!memeBitmap.isRecycled())
        {
            memeBitmap.recycle();
            memeBitmap = null;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

  

@ AC-OpenSource E / BitmapFactory:无法解码流:   java.io.FileNotFoundException:   /http:/static2.businessinsider.com/image/56e3189152bcd0320c8 b5cf7-480 /萨米 - 笑容ER成功 - 孩子 - meme. JPG:   打开失败:ENOENT(没有这样的文件或目录)

你在http

之前有一个斜杠