Android: как получить случайное изображение из массива без повторов с JSON в качестве источника - PullRequest
0 голосов
/ 18 апреля 2011

У меня проблемы с получением случайных изображений (в виде кнопок) из массива без повторений с использованием файла JSON в Интернете в качестве источника.Каждая кнопка onClick приводит к действию с свойствами объекта, отличными от JSON, в зависимости от отображаемого изображения.

Поэтому я помещу 3 таких изображения в действие, но они не могут быть одинаковыми сдруг друга.

Может ли кто-нибудь помочь мне найти решение из приведенных ниже кодов?Я открыт для любых решений.Заранее спасибо.

Вот фрагмент моего JSON, я хочу использовать свойство smallImageUrl.

{
  "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):

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:

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

открытый класс ProjectAdapterрасширяет 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;
}

}

1 Ответ

1 голос
/ 18 апреля 2011

Хороший пример с объяснением:

Загрузка изображений по HTTP в отдельном потоке на Android

и использование примера:

Загрузка удаленных изображений в ListView на Android

В первом примере это ImageThreadLoader, который имеет метод loadImage. Метод получает растровое изображение из кэша или, если его нет, загружает его из сети.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...