安卓:额外的传递从一个活动到另一个活动

2023-09-06 05:22:26 作者:人生警戒线

我有被填充到一个活动(Main.java)。一个JSON文件

此活动显示了我的JSON项从URL 3随机图像。

我想要做的是:我对我的JSON,每当我点击它转到包含图片,标题另一个活动(ProjectDetail.java)所示随机​​图片13不同的条目,并说明取决于我点击项目根据它的JSON条目。

什么我有是使用额外的由我不知道究竟如何,因为我使用JSON来执行。我应该加入到我的 top_listener 方法对我的主类,我应该加入到我的ProjectDetail类?

感谢您。

Main.java

 公共类主要活动扩展{            / **当第一次创建活动调用。 * /            ArrayList的<项目> prjcts = NULL;            私人ImageThreadLoader ImageLoader的=新ImageThreadLoader();            私人最终静态字符串变量=MediaItemAdapter;            @覆盖            公共无效的onCreate(捆绑savedInstanceState){                super.onCreate(savedInstanceState);                的setContentView(R.layout.main);                prjcts =新的ArrayList<项目>();                WebService的web服务=新的WebService(http://liebenwald.spendino.net/admanager/dev/android/projects.json);                地图<字符串,字符串> PARAMS =新的HashMap<字符串,字符串>();                params.put(变种,);                字符串的响应= webService.webGet(,则params);                尝试                {                    键入collectionType =新TypeToken< ArrayList的<项目及GT;>(){}的getType()。                    清单<项目> 。LST =新GSON()fromJson(响应,collectionType);                    对于(项目L:LST)                    {                        prjcts.add(升);                        ConstantData.projectsList.add(升);                    }                }                赶上(例外五)                {                    Log.d(错误,e.getMessage());                }                最终巴顿项目=(按钮)findViewById(R.id.btn_projectslist);                最终按钮的相关信息=(按钮)findViewById(R.id.btn_infos);                最终按钮触点=(按钮)findViewById(R.id.btn_contact);                project.setOnClickListener(project_listener);                infos.setOnClickListener(infos_listener);                contact.setOnClickListener(contact_listener);                ImageView的image1的;                ImageView的IMAGE2;                ImageView的图像3;                尝试{                    此搜索=(ImageView的)findViewById(R.id.top1);                    IMAGE2 =(ImageView的)findViewById(R.id.top2);                    图像3 =(ImageView的)findViewById(R.id.top3);                  }赶上(抛出ClassCastException E){                    Log.e(TAG,你的布局必须提供图像,并与ID的图标和文字文本视图,E);                    Ë扔掉;                  }                  位图cachedImage1 = NULL;                  位图cachedImage2 = NULL;                  位图cachedImage3 = NULL;                  //随机图像项的索引                  INT最大= prjcts.size();                  清单<整数GT;指数=新的ArrayList<整数GT;(最大值);                  对(INT C = 0;℃下最大++三)                  {                      indices.add(C);                  }                  INT arrIndex =(INT)((双)indices.size()*的Math.random());                  INT randomIndex1 = indices.get(arrIndex);                  indices.remove(arrIndex);                  INT randomIndex2 = indices.get(arrIndex);                  indices.remove(arrIndex);                  INT randomIndex3 = indices.get(arrIndex);                  indices.remove(arrIndex);                  setImage(cachedImage1,此搜索,prjcts.get(randomIndex1));                  setImage(cachedImage2,图像2,prjcts.get(randomIndex2));                  setImage(cachedImage3,为image3,prjcts.get(randomIndex3));                  image1.setOnClickListener(top_listener);                  image2.setOnClickListener(top_listener);                  image3.setOnClickListener(top_listener);            }            公共无效setImage(位图cachedImage,最终ImageView的形象,项目PRO)            {                //位图cachedImage1 = NULL;                尝试{                    cachedImage = imageLoader.loadImage(pro.smallImageUrl,新ImageLoadedListener()                    {                        公共无效imageLoaded(位图imageBitmap)                        {                            image.setImageBitmap(imageBitmap);                            // notifyDataSetChanged();                        }                    });                }赶上(MalformedURLException的E){                    Log.e(TAG,坏遥感图像URL:+ pro.smallImageUrl,E);                }                如果(cachedImage!= NULL){                    image.setImageBitmap(cachedImage);                  }            }            私人OnClickListener top_listener =新OnClickListener(){                公共无效的onClick(视图v){                            意图顶部=新意图(Main.this,InfosActivity.class);                            startActivity(顶部);                }                }; 
谷歌安卓上新功能 用脸就能控制手机

ProjectDetail.java

 公共类ProjectDetail扩展活动实现OnClickListener {    @覆盖    公共无效的onCreate(捆绑savedInstanceState){        super.onCreate(savedInstanceState);        的setContentView(R.layout.project);        按钮weitersagen =(按钮)findViewById(R.id.btn_weitersagen);        weitersagen.setOnClickListener(本);        按钮短信=(按钮)findViewById(R.id.btn_sms_spenden);        sms.setOnClickListener(本);        INT位置= getIntent()getExtras()调用getInt(spendino.de.ProjectDetail.position)。;        项目项目= ConstantData.projectsList.get(位置);      尝试{          ImageView的projectImage =(ImageView的)findViewById(R.id.project_image);          位图位图= BitmapFactory.de codeStream((InputStream的)新的URL(project.bigImageUrl).getContent());          projectImage.setImageBitmap(位图);        }赶上(MalformedURLException的E){          e.printStackTrace();        }赶上(IOException异常五){          e.printStackTrace();        }      TextView的PROJECT_TITLE =(的TextView)findViewById(R.id.txt_project_title);      project_title.setText(project.project_title);      TextView的ORGANIZATION_TITLE =(的TextView)findViewById(R.id.txt_organization_title);      organization_title.setText(Html.fromHtml(冯+ project.organization_title));      TextView的project_description =(的TextView)findViewById(R.id.txt_project_description);      project_description.setText(Html.fromHtml(project.project_description));    } 

我也有这个 ConstantData.java ,其持有我的JSON性能指标:

 公共类ConstantData {   公共静态字符串PROJECT_TITLE =项目名称;   公共静态字符串ORGANIZATION_TITLE =单位名称;   公共静态字符串关键字=关键词;   公共静态字符串short_ code =短code;   公共静态字符串project_description =说明;   公共静态字符串smallImageUrl =smallImageUrl;   公共静态字符串bigImageUrl =bigImageUrl;   公共静态字符串价=价格;   公共静态字符串国家=国家;    公共静态的ArrayList<项目> projectsList =新的ArrayList<项目>();    公众诠释describeContents(){        返回0;    }    公共无效writeToParcel(包裹出来,诠释标志){        out.writeString(PROJECT_TITLE);        out.writeString(ORGANIZATION_TITLE);        out.writeString(关键字);        out.writeString(short_ code);        out.writeString(project_description);        out.writeString(smallImageUrl);        out.writeString(bigImageUrl);        out.writeString(价);        out.writeString(国家);    }    公共静态最终Parcelable.Creator< ConstantData> CREATOR            =新Parcelable.Creator< ConstantData>(){        公共ConstantData createFromParcel(包裹中){            返回新ConstantData(中);        }        公共ConstantData [] newArray(INT大小){            返回新ConstantData【尺寸】;        }    };    私人ConstantData(包裹中){        PROJECT_TITLE = in.readString();        ORGANIZATION_TITLE = in.readString();        关键字= in.readString();        short_ code = in.readString();        project_description = in.readString();        smallImageUrl = in.readString();        bigImageUrl = in.readString();        价格= in.readString();        国家= in.readString();    }} 

解决方案

您可以使类ConstantData由Parcelable扩展和实现两个方法(可串行看到的文档)。然后,你可以通过做传递一个constantData实例作为一个额外的

  intent.putExtra(jsonData,constantDataInstance); 

和从其他活动中检索它(在它的onCreate()方法)与

  getIntent()getExtras()getParcelable(jsonData)。; 

否则,你可能只是过去那样额外各个领域的独立,但它是一个烂摊子。这种方式不仅更易于阅读和一切,但精心设计。

I have a JSON file which is populated to an activity (Main.java).

This Activity shows 3 random images from the URL on my JSON entries.

What I wanna do is: I have 13 different entries on the my JSON, whenever I click the shown random picture it goes to another activity (ProjectDetail.java) containing the picture,title,and description depends on the item I click based on its entry on the JSON.

What do I have in is by using extra by I dont know exactly how to perform that since I'm using JSON. What should I add into my top_listener method on my Main class and what should I add into my ProjectDetail class?

Thank you.

Main.java

   public class Main extends Activity {
            /** Called when the activity is first created. */

            ArrayList<Project> prjcts=null;
            private ImageThreadLoader imageLoader = new ImageThreadLoader();
            private final static String TAG = "MediaItemAdapter";


            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.main);

                prjcts = new ArrayList<Project>();
                WebService webService = new WebService("http://liebenwald.spendino.net/admanager/dev/android/projects.json");
                Map<String, String> params = new HashMap<String, String>();
                params.put("var", "");
                String response = webService.webGet("", params);

                try
                {
                    Type collectionType = new TypeToken<ArrayList<Project>>(){}.getType();
                    List<Project> lst= new Gson().fromJson(response, collectionType);
                    for(Project l : lst)
                    {
                        prjcts.add(l);
                        ConstantData.projectsList.add(l);
                    }
                }
                catch(Exception e)
                {
                    Log.d("Error: ", e.getMessage());
                }

                final Button project = (Button) findViewById(R.id.btn_projectslist);
                final Button infos = (Button) findViewById(R.id.btn_infos);
                final Button contact = (Button) findViewById(R.id.btn_contact);
                project.setOnClickListener(project_listener);
                infos.setOnClickListener(infos_listener);
                contact.setOnClickListener(contact_listener);

                ImageView image1;
                ImageView image2;
                ImageView image3;

                try {
                    image1 = (ImageView)findViewById(R.id.top1);
                    image2 = (ImageView)findViewById(R.id.top2);
                    image3 = (ImageView)findViewById(R.id.top3);
                  } catch( ClassCastException e ) {
                    Log.e(TAG, "Your layout must provide an image and a text view with ID's icon and text.", e);
                    throw e;
                  }


                  Bitmap cachedImage1 = null;
                  Bitmap cachedImage2 = null;
                  Bitmap cachedImage3 = null;

                  //randomize the index of image entry

                  int max = prjcts.size();
                  List<Integer> indices = new ArrayList<Integer>(max);
                  for(int c = 0; c < max; ++c)
                  {
                      indices.add(c);
                  }

                  int arrIndex = (int)((double)indices.size() * Math.random());
                  int randomIndex1 = indices.get(arrIndex);
                  indices.remove(arrIndex);


                  int randomIndex2 = indices.get(arrIndex);
                  indices.remove(arrIndex);


                  int randomIndex3 = indices.get(arrIndex);
                  indices.remove(arrIndex);



                  setImage(cachedImage1, image1, prjcts.get(randomIndex1));
                  setImage(cachedImage2, image2, prjcts.get(randomIndex2));
                  setImage(cachedImage3, image3, prjcts.get(randomIndex3));

                  image1.setOnClickListener(top_listener);
                  image2.setOnClickListener(top_listener);
                  image3.setOnClickListener(top_listener);
            }



            public void setImage(Bitmap cachedImage, final ImageView image, Project pro)
            {
                //Bitmap cachedImage1 = null;
                try {
                    cachedImage = imageLoader.loadImage(pro.smallImageUrl, new ImageLoadedListener() 
                    {
                        public void imageLoaded(Bitmap imageBitmap)
                        {
                            image.setImageBitmap(imageBitmap);
                            //notifyDataSetChanged();                
                        }
                    });
                } catch (MalformedURLException e) {
                    Log.e(TAG, "Bad remote image URL: " + pro.smallImageUrl, e);
                }
                if( cachedImage != null ) {
                    image.setImageBitmap(cachedImage);
                  }
            }


            private OnClickListener top_listener = new OnClickListener() {
                public void onClick(View v) {
                            Intent top = new Intent(Main.this, InfosActivity.class);
                            startActivity(top);
                }
                };

ProjectDetail.java

public class ProjectDetail extends Activity implements OnClickListener{


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.project);

        Button weitersagen = (Button) findViewById(R.id.btn_weitersagen);
        weitersagen.setOnClickListener(this);

        Button sms = (Button) findViewById(R.id.btn_sms_spenden);
        sms.setOnClickListener(this);

        int position = getIntent().getExtras().getInt("spendino.de.ProjectDetail.position");
        Project project = ConstantData.projectsList.get(position);


      try {
          ImageView projectImage = (ImageView)findViewById(R.id.project_image);
          Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(project.bigImageUrl).getContent());
          projectImage.setImageBitmap(bitmap); 
        } catch (MalformedURLException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        } 

      TextView project_title = (TextView)findViewById(R.id.txt_project_title);
      project_title.setText(project.project_title);

      TextView organization_title = (TextView)findViewById(R.id.txt_organization_title);
      organization_title.setText(Html.fromHtml("von " +project.organization_title));

      TextView project_description = (TextView)findViewById(R.id.txt_project_description);
      project_description.setText(Html.fromHtml(project.project_description));

    }

I also have this ConstantData.java, the index which holds my JSON properties:

 public class ConstantData{

   public static String project_title = "project title";
   public static String organization_title = "organization title";
   public static String keyword = "keyword";
   public static String short_code = "short code";
   public static String project_description = "description";
   public static String smallImageUrl = "smallImageUrl";
   public static String bigImageUrl = "bigImageUrl";
   public static String price= "price";
   public static String country= "country";



    public static ArrayList<Project> projectsList = new ArrayList<Project>();


    public int describeContents() {
        return 0;
    }

    public void writeToParcel(Parcel out, int flags) {
        out.writeString(project_title);
        out.writeString(organization_title);
        out.writeString(keyword);
        out.writeString(short_code);
        out.writeString(project_description);
        out.writeString(smallImageUrl);
        out.writeString(bigImageUrl);
        out.writeString(price);
        out.writeString(country);
    }

    public static final Parcelable.Creator<ConstantData> CREATOR
            = new Parcelable.Creator<ConstantData>() {
        public ConstantData createFromParcel(Parcel in) {
            return new ConstantData(in);
        }

        public ConstantData[] newArray(int size) {
            return new ConstantData[size];
        }
    };

    private ConstantData(Parcel in) {
        project_title = in.readString();
        organization_title = in.readString();
        keyword = in.readString();
        short_code = in.readString();
        project_description = in.readString();
        smallImageUrl = in.readString();
        bigImageUrl = in.readString();
        price = in.readString();
        country = in.readString();
    }
}

解决方案

You could make the class ConstantData serializable by extending from Parcelable and implementing a couple of methods (see the documentation). Then you could pass a constantData instance as an extra by doing

intent.putExtra("jsonData", constantDataInstance);

and retrieving it from the other activity (in it's onCreate() method) with

getIntent().getExtras().getParcelable("jsonData");

Otherwise you could just past as extra every field independently, but it would be a mess. This way is not only more easy to read and everything, but "well designed".

相关推荐