Android的:如何从数组随机图像没有重复使用JSON作为源 [英] Android: How to get random image from array without repetition with JSON as the source

查看:206
本文介绍了Android的:如何从数组随机图像没有重复使用JSON作为源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有在获得从阵列随机图像(如按钮),而不使用网络作为源的JSON文件的重复的麻烦。每个按钮的onClick导致从JSON根据所显示的图像在不同的对象属性的活动。

I'm having trouble in getting random images (as buttons) from array without repetition with JSON file on the web as the source. Each onClick button leads to an activity with different object properties from the JSON based on the displayed image.

所以我把这些实物图像3的活动里面,但他们不能与对方相同的。

So I will put 3 of those kind images inside an activity, but they aren't allowed to be the same with each other.

有人可以帮助我提供解决方案,我的$ C $低于CS的?我接受任何类型的解决方案。先谢谢了。

Can someone help me providing the solution out of my codes below? I'm open to any kind of solutions. Thanks in advance.

下面是我的JSON的片段,我想使用的是smallImageUrl'属性。

Here's the snippet of my JSON, what I wanna use is the 'smallImageUrl' property.

{
  "project_title": "Deutsche Gesellschaft zur Rettung Schiffbrüchiger",
  "organization_title": "Deutsche Gesellschaft zur Rettung Schiffbrüchiger",
  "keyword": "RETTER",
  "short_code":"81190",
  "project_description": "Seit Mitte des 19. Jahrhunderts schenken die Seenotretter Schiffsbrüchigen ein zweites Leben. Die Aufgaben der Organisation umfassen dabei alle Bereiche – vom Abhören der Funkverkehrfrequenzen bis zum sicheren Transport erstversorgter Menschen.  61 Seenotkreuzer und Seenotrettungsboote sind dafür 24 Stunden am Tag, sieben Tage die Woche, bei jedem Wind und Wetter einsatzbereit. Das humanitäre Wirken der Organisation wird dabei nur durch Förderer ermöglicht, denn die DGzRS ist ausschließlich spendenfinanziert. ",
  "smallImageUrl": "http://cdn.spendino.de/web/img/projects/home/1298899521.jpg",
  "bigImageUrl":"http://cdn.spendino.de/web/img/projects/small/1298899521.jpg",
  "price": "5 EUR",
  "country": "Germany"
  },
  {
  "project_title": "CARE Deutschland-Luxemburg e.V.",
  "organization_title": "CARE Deutschland-Luxemburg e.V.",
  "keyword": "CARE",
  "short_code":"81190",
  "project_description": "<p><b>Das CARE-Komplett-Paket für Menschen in Not</b></p><p>Schnell, nachhaltig und durchdacht, das ist das moderne CARE-Paket. CARE ist überzeugt, dass umfassende Hilfe von drei Seiten notwendig ist, um die weltweite Armut Schritt für Schritt zu verringern. Deswegen hat CARE sich seit seiner Gründung 1945 und dem Abwurf der ersten CARE-Pakete über Berlin weiter entwickelt. Heute steckt im CARE-Paket weit mehr als Zucker und Mehl. Heute bietet die Organisation in 70 der ärmsten Länder der Welt ein Komplett-Paket für Menschen in Not.</p><p><b>Das Komplett-Paket für Menschen in Not enthält:</b></p>*sofortige Nothilfe nach Katastrophen<br><br>*langfristige Entwicklungszusammenarbeit<br><br>*Schutz der Menschenrechte<br><br>",
  "smallImageUrl": "http://cdn.spendino.de/web/img/projects/home/1284113658.jpg",
  "bigImageUrl":"http://cdn.spendino.de/web/img/projects/small/1284113658.jpg",
  "price": "5 EUR",
  "country": "Germany"
  },

我所说的JSON的解析方法,从下面这个ListActivity,但实际上现在我的工作活动,显示了随机图像,有来作为一个启动器(在ListActivity前):

I call the JSON-parsing method from this ListActivity below, but actually the activity I'm working right now which shows the random images, has to come as a launcher (before the ListActivity):

public class ProjectsList extends Activity {
    /** Called when the activity is first created. */
    //ListView that will hold our items references back to main.xml
    ListView lstTest;
    //Array Adapter that will hold our ArrayList and display the items on the ListView
    ProjectAdapter arrayAdapter;
    ProgressDialog dialog;

    //List that will  host our items and allow us to modify that array adapter
    ArrayList<Project> prjcts=null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.projects_list);
        //Initialize ListView
        lstTest= (ListView)findViewById(R.id.lstText);

         //Initialize our ArrayList
        prjcts = new ArrayList<Project>();
        //Initialize our array adapter notice how it references the listitems.xml layout
        arrayAdapter = new ProjectAdapter(ProjectsList.this, R.layout.listitems,prjcts);

        //Set the above adapter as the adapter of choice for our list
        lstTest.setAdapter(arrayAdapter);



        WebService webService = new WebService("http://liebenwald.spendino.net/admanager/dev/android/projects.json");

        //Pass the parameters if needed , if not then pass dummy one as follows
        Map<String, String> params = new HashMap<String, String>();
        params.put("var", "");

        //Get JSON response from server the "" are where the method name would normally go if needed example
        // webService.webGet("getMoreAllerts", params);
        String response = webService.webGet("", params);

        try
        {
             dialog = ProgressDialog.show(ProjectsList.this, "", "Fetching Projects...", true);
             dialog.setCancelable(true);
             dialog.setCanceledOnTouchOutside(true);
             dialog.setOnCancelListener(new OnCancelListener() {
                public void onCancel(DialogInterface dialog) {

                }
             });
            //Parse Response into our object
            Type collectionType = new TypeToken<ArrayList<Project>>(){}.getType();

            //JSON expects an list so can't use our ArrayList from the lstart
            List<Project> lst= new Gson().fromJson(response, collectionType);


            //Now that we have that list lets add it to the ArrayList which will hold our items.
            for(Project l : lst)
            {
                prjcts.add(l);
                ConstantData.projectsList.add(l);
            }

            //Since we've modified the arrayList we now need to notify the adapter that
            //its data has changed so that it updates the UI
            arrayAdapter.notifyDataSetChanged();
            dialog.dismiss();
        }
        catch(Exception e)
        {
            Log.d("Error: ", e.getMessage());
        }

        lstTest.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {              
                //@SuppressWarnings("unchecked")
                //Projects p = (Projects ) lstTest.getItemAtPosition(position);     

                //Do your logic and open up a new Activity.
                Intent care = new Intent(ProjectsList.this, ProjectDetail.class);
                care.putExtra("spendino.de.Organization.position",position);
                startActivity(care);
            }
        });

    }
}

这里是它握住我的JSON的指数类:

here's the class which hold the index of my JSON:

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

和这是活性,其中所​​述随机按钮应导致

and this is the activity where the random buttons should lead to:

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

    }

修改
这里是我的ProjectAdapter为ListActivity

EDIT Here's my ProjectAdapter for the ListActivity

公共类ProjectAdapter扩展ArrayAdapter {

public class ProjectAdapter extends ArrayAdapter {

int resource;
String response;
Context context;
//Initialize adapter
public ProjectAdapter(Context context, int resource, List<Project> items) {
    super(context, resource, items);
    this.resource=resource;

}



@Override
public View getView(int position, View convertView, ViewGroup parent)
{
    LinearLayout projectView;
    //Get the current alert object
    Project pro = getItem(position);

    //Inflate the view
    if(convertView==null)
    {
        projectView = new LinearLayout(getContext());
        String inflater = Context.LAYOUT_INFLATER_SERVICE;
        LayoutInflater vi;
        vi = (LayoutInflater)getContext().getSystemService(inflater);
        vi.inflate(resource, projectView, true);
    }
    else
    {
        projectView = (LinearLayout) convertView;
    }

    TextView Title =(TextView)projectView.findViewById(R.id.txt_title);

    try {
          ImageView i = (ImageView)projectView.findViewById(R.id.image);
          Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(pro.smallImageUrl).getContent());
          i.setImageBitmap(bitmap); 
        } catch (MalformedURLException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }


    //Assign the appropriate data from our alert object above
    //Image.setImageDrawable(pro.smallImageUrl);
    Title.setText(pro.project_title);

    return projectView;
}

}

推荐答案

用好交代例如:

<一个href=\"http://ballardhack.word$p$pss.com/2010/04/10/loading-images-over-http-on-a-separate-thread-on-android/\"相对=nofollow>加载图像在HTTP上一个单独的线程在Android

和例子的用法:

在Android 一个ListView加载远程图像

Loading Remote Images in a ListView on Android

在第一个例子是具有的LoadImage方法ImageThreadLoader。该方法从缓存中获取位图或如果它不是present,从网络下载它。

In the first example is ImageThreadLoader which has loadImage method. The method gets bitmap from cache or if it's not present, downloads it from network.

这篇关于Android的:如何从数组随机图像没有重复使用JSON作为源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆