Android: How to get random image from array without repetition with JSON as the source
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.
So I will put 3 of those kind images inside an activity, but they aren't allowed to be the same with each other.
Can someone help me providing the solution out of my codes below? I'm open to any kind of solutions. Thanks in advance.
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"
},
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 OnIt开发者_如何转开发emClickListener() {
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);
}
});
}
}
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));
}
EDIT Here's my ProjectAdapter for the ListActivity
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;
}
}
Good example with explaination:
Loading Images Over HTTP on a Separate Thread on Android
and usage of the example:
Loading Remote Images in a ListView on Android
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.
精彩评论