如何让gridview类在单击时调用自身,然后在另一个网格项上单击,引用另一个活动?

时间:2016-03-31 04:45:40

标签: java android android-intent gridview onitemclick

另一个类调用下面的 GridView 类,该类填充了来自解析服务器的图像,如果用户点击网格项,它会启动相同的 GridView 类不同的捆绑字符串,因此它可以从不同的解析数据库类中提取。现在,此时,当用户单击GridView项目(来自设置的第二个gridview)时,我希望它启动另一个活动类。

我尝试在onItemClick中执行if / else if语句,该语句采用" PARSE_CLASS "捆绑的字符串,但我似乎无法让它工作。我对android编程比较陌生,所以我不知道最好的方法。

    public class DisplayGrid extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

    GridView gridView = null;
    List<ParseObject> obj;
    ProgressDialog loadProgress;
    GridViewAdapter adapter;
    Bundle extras = new Bundle();
    GridViewAdapter itemGridAdapter;
    private List<ImageList> imageArrayList = null;
    private List<String> categoryNameArrayList = null;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ws_display_grid);
        imageArrayList = new ArrayList<ImageList>();
        categoryNameArrayList = new ArrayList<String>();
        gridView = (GridView) findViewById(R.id.gridView);
        itemGridAdapter = new GridViewAdapter(DisplayGrid.this, imageArrayList);
        gridView.setAdapter(itemGridAdapter);



        new RemoteDataTask().execute();

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            Intent i = getIntent();
            Bundle itemExtras = i.getExtras();
            final String activeSupplier = itemExtras.getString("SUPPLIER");
            String parseClass = extras.getString("PARSE_CLASS");

            @Override
            public void onItemClick(AdapterView<?> arg0, View v, int position,
                                    long arg3) {
                    Intent t = new Intent(getApplicationContext(), DisplayGrid.class);
                    extras.putString("SUPPLIER", activeSupplier);
                    extras.putString("PARSE_CLASS", "Items");
                    t.putExtras(extras);
                    startActivity(t);

            }
        });
    }//end onCreate method


    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
    }


    //RemoteDataTask
    private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loadProgress = new ProgressDialog(DisplayGrid.this);
            loadProgress.setTitle("Images");
            loadProgress.setMessage("Loading...");
            loadProgress.setIndeterminate(false);
            loadProgress.show();
        }

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


            try {
                Intent i = getIntent();
                Bundle extras = i.getExtras();

                String parseClass = extras.getString("PARSE_CLASS");
                String activeSupplier = extras.getString("SUPPLIER");

                String category;

                ParseQuery<ParseObject> query = new ParseQuery<>(parseClass);
                query.whereEqualTo("username", activeSupplier);
                obj = query.find();
                if (parseClass == "Items") {
                    category = extras.getString("CATEGORY");
                    query.whereEqualTo("category", category);

                }
                for (ParseObject categories : obj) {
                    //get image
                    ParseFile image = (ParseFile) categories.get("image");
                    ImageList gridBlock = new ImageList();
                    gridBlock.setImage(image.getUrl());
                    imageArrayList.add(gridBlock);
                    Log.i("AppInfo", "image sent to imageArrayList");

                    String categoryName = null;
                    //get category name
                    if (categoryName == null) {

                    } else {
                        categoryName = categories.getString("categoryName");
                        categoryNameArrayList.add(categoryName);
                        Log.i("AppInfo", categoryName);
                    }
                }
            } catch (ParseException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            gridView = (GridView) findViewById(R.id.gridView);
            adapter = new GridViewAdapter(DisplayGrid.this, imageArrayList);
            gridView.setAdapter(adapter);
            loadProgress.dismiss();
            Log.i("AppInfo", "CategoryGrid Populated");
        }


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
            Uri selectedImage = data.getData();
            try {
                Bitmap bitmapImage =
                        MediaStore.Images.Media.getBitmap
                                (this.getContentResolver(), selectedImage);

                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
                byte[] byteArray = stream.toByteArray();

                //convert to parse file
                ParseFile file = new ParseFile("Img.png", byteArray);

                ParseObject object = new ParseObject("Categories");
                object.put("username", ParseUser.getCurrentUser().getUsername());
                object.put("image", file);

                object.saveInBackground(new SaveCallback() {
                    @Override
                    public void done(ParseException e) {
                        if (e == null) {
                            Toast.makeText(getApplication().getBaseContext(), "Your image has been saved", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getApplication().getBaseContext(), "Upload failed, please try again", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(getApplication().getBaseContext(), "Upload failed, please try again", Toast.LENGTH_SHORT).show();
            }
        }
    }

    //begin getTitle method

    //begin createMenu
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        new MenuInflater(getApplication())
                .inflate(R.menu.options, menu);

        return (super.onCreateOptionsMenu(menu));
    }
    //end createMenu

    //begin onOptionsItemSelected
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {


        if (item.getItemId() == R.id.manufacturers) {
            Intent i = new Intent(getApplicationContext(), SupplierList.class);
            startActivity(i);
            return true;
        } else if (item.getItemId() == R.id.add) {
            Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(i, 1);
            return true;
        } else if (item.getItemId() == R.id.sign_out) {
            ParseUser.logOut();

            Intent i = new Intent(getApplicationContext(), MainActivity.class);
            startActivity(i);
            return true;
        }

        return (super.onOptionsItemSelected(item));
    }
    //end onOptionsItemSelected
}

这就是我尝试过的。当我尝试这个时,第二个 GridView 将无法加载。因此,我猜测我第二次无法检索&#34; PARSE_CLASS&#34; 捆绑字符串。

gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        Intent i = getIntent();
        Bundle itemExtras = i.getExtras();
        final String activeSupplier = itemExtras.getString("SUPPLIER");
        String parseClass = extras.getString("PARSE_CLASS");

        @Override
        public void onItemClick(AdapterView<?> arg0, View v, int position,
                                long arg3) {
            if (parseClass == "Categories") {
                Intent t = new Intent(getApplicationContext(), DisplayGrid.class);
                extras.putString("SUPPLIER", activeSupplier);
                extras.putString("PARSE_CLASS", "Items");
                t.putExtras(extras);
                startActivity(t);
            } else if(parseClass == "Items"){
                Intent t = new Intent(getApplicationContext(), ItemDisplay.class);
                //extras.putString("SUPPLIER", activeSupplier);
                //extras.putString("PARSE_CLASS", "Items");
                //t.putExtras(extras);
                startActivity(t);
            }

        }
    }); 

ANSWER 有人在reddit上学习编程很好,可以指出我遇到了字符串比较的问题。不得不使用

if(parseClass.equals("Categories")){}

而不是

if(parseClass == "Categories"){}

我觉得自己像个白痴,希望其他人能从这个长期的灾难性努力中受益。

gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        Intent t = getIntent();
        Bundle itemExtras = t.getExtras();
        String activeSupplier = itemExtras.getString("SUPPLIER");
        String parseClass = itemExtras.getString("PARSE_CLASS");

        @Override
        public void onItemClick(AdapterView<?> arg0, View v, int position,
                                long arg3) {
            Log.i("AppInfo", parseClass);

            if (parseClass.equals("Categories")) {
                Log.i("AppInfo", parseClass);
                Intent t = new Intent(getApplicationContext(), DisplayGrid.class);
                String categoryName = categoryNameArrayList.get(position);

                itemExtras.putString("SUPPLIER", activeSupplier);
                itemExtras.putString("PARSE_CLASS", "Items");
                itemExtras.putString("CATEGORY_NAME", categoryName);
                t.putExtras(itemExtras);
                startActivity(t);
            } else if (parseClass.equals("Items")) {
                Intent t = new Intent(getApplicationContext(), ItemDisplay.class);
                //extras.putString("SUPPLIER", activeSupplier);
                //extras.putString("PARSE_CLASS", "Items");
                //t.putExtras(extras);
                startActivity(t);
            }
        }
    });

1 个答案:

答案 0 :(得分:0)

public class DisplayGrid extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

    GridView gridView = null;
    List<ParseObject> obj;
    ProgressDialog loadProgress;
    GridViewAdapter adapter;
    Bundle extras = new Bundle();
    GridViewAdapter itemGridAdapter;
    private List<ImageList> imageArrayList = null;
    private List<String> categoryNameArrayList = null;
    String activeSupplier;
    String parseClass;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ws_display_grid);
        imageArrayList = new ArrayList<ImageList>();
        categoryNameArrayList = new ArrayList<String>();
        Intent i = getIntent();
        if (null != i) {
            Bundle itemExtras = i.getExtras();
            activeSupplier = itemExtras.getString("SUPPLIER");
            parseClass = itemExtras.getString("PARSE_CLASS");
        }
        RemoteDataTask remoteDataAsync = new RemoteDataTask();
        remoteDataAsync.execute();

        if(remoteDataAsync.getStatus() == AsyncTask.Status.PENDING){
            // My AsyncTask has not started yet
        }

        if(remoteDataAsync.getStatus() == AsyncTask.Status.RUNNING){
            // My AsyncTask is currently doing work in doInBackground()
        }

        if(remoteDataAsync.getStatus() == AsyncTask.Status.FINISHED){
            // My AsyncTask is done and onPostExecute was called
            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {


                @Override
                public void onItemClick(AdapterView<?> arg0, View v, int position,
                                        long arg3) {
                    Intent t = new Intent(getApplicationContext(), DisplayGrid.class);
                    extras.putString("SUPPLIER", activeSupplier);
                    extras.putString("PARSE_CLASS", parseClass);
                    t.putExtras(extras);
                    startActivity(t);

                }
            });
        }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
    }


    //RemoteDataTask
    private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loadProgress = new ProgressDialog(DisplayGrid.this);
            loadProgress.setTitle("Images");
            loadProgress.setMessage("Loading...");
            loadProgress.setIndeterminate(false);
            loadProgress.show();
        }

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


            try {
                Intent i = getIntent();
                Bundle extras = i.getExtras();

                String parseClass = extras.getString("PARSE_CLASS");
                String activeSupplier = extras.getString("SUPPLIER");

                String category;

                ParseQuery<ParseObject> query = new ParseQuery<>(parseClass);
                query.whereEqualTo("username", activeSupplier);
                obj = query.find();
                if (parseClass == "Items") {
                    category = extras.getString("CATEGORY");
                    query.whereEqualTo("category", category);

                }
                for (ParseObject categories : obj) {
                    //get image
                    ParseFile image = (ParseFile) categories.get("image");
                    ImageList gridBlock = new ImageList();
                    gridBlock.setImage(image.getUrl());
                    imageArrayList.add(gridBlock);
                    Log.i("AppInfo", "image sent to imageArrayList");

                    String categoryName = null;
                    //get category name
                    if (categoryName == null) {

                    } else {
                        categoryName = categories.getString("categoryName");
                        categoryNameArrayList.add(categoryName);
                        Log.i("AppInfo", categoryName);
                    }
                }
            } catch (ParseException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {

            adapter = new GridViewAdapter(DisplayGrid.this, imageArrayList);
            gridView.setAdapter(adapter);
            loadProgress.dismiss();
            Log.i("AppInfo", "CategoryGrid Populated");

        }//end onCreate method
        }


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
            Uri selectedImage = data.getData();
            try {
                Bitmap bitmapImage =
                        MediaStore.Images.Media.getBitmap
                                (this.getContentResolver(), selectedImage);

                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
                byte[] byteArray = stream.toByteArray();

                //convert to parse file
                ParseFile file = new ParseFile("Img.png", byteArray);

                ParseObject object = new ParseObject("Categories");
                object.put("username", ParseUser.getCurrentUser().getUsername());
                object.put("image", file);

                object.saveInBackground(new SaveCallback() {
                    @Override
                    public void done(ParseException e) {
                        if (e == null) {
                            Toast.makeText(getApplication().getBaseContext(), "Your image has been saved", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getApplication().getBaseContext(), "Upload failed, please try again", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(getApplication().getBaseContext(), "Upload failed, please try again", Toast.LENGTH_SHORT).show();
            }
        }
    }

    //begin getTitle method

    //begin createMenu
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        new MenuInflater(getApplication())
                .inflate(R.menu.options, menu);

        return (super.onCreateOptionsMenu(menu));
    }
    //end createMenu

    //begin onOptionsItemSelected
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {


        if (item.getItemId() == R.id.manufacturers) {
            Intent i = new Intent(getApplicationContext(), SupplierList.class);
            startActivity(i);
            return true;
        } else if (item.getItemId() == R.id.add) {
            Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(i, 1);
            return true;
        } else if (item.getItemId() == R.id.sign_out) {
            ParseUser.logOut();

            Intent i = new Intent(getApplicationContext(), MainActivity.class);
            startActivity(i);
            return true;
        }

        return (super.onOptionsItemSelected(item));
    }
    //end onOptionsItemSelected
}