android


OnItemClickListener in gridview duplicate


I'm new in android and trying to create gridview with selected elements.
If I use OnItemClickListener and change e.g. alpha of the view It would change 2 images instead of 1.
I don't know where is a problem. Please give any advices :)
MainActivity.java
package com.example.collage;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import android.accounts.NetworkErrorException;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
static String CLIENT_ID = "1c77d0e90073461a8d16e70eb040e407";
String user_id;
ArrayList<Photo> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
TextView edittext1 = (TextView) findViewById(R.id.editText1);
if (edittext1.getText().toString().length() == 0) {
Toast.makeText(getApplicationContext(), "Введите логин",
Toast.LENGTH_SHORT).show();
} else {
String url = "https://api.instagram.com/v1/users/search?q="
+ edittext1.getText().toString() + "&client_id="
+ CLIENT_ID;
MyTask response = new MyTask();
try {
user_id = response.execute(url).get();
if (user_id != "") {
String url2 = "https://api.instagram.com/v1/users/"
+ user_id + "/media/recent/?client_id=" + CLIENT_ID;
PhotoList photos = new PhotoList();
list = photos.execute(url2).get();
}
Intent intent = new Intent(MainActivity.this,
Photo_picker.class);
Photo_picker.setViews(Photo.getDrawable(list));
startActivity(intent);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private String readUrl(String urlString) throws Exception {
BufferedReader reader = null;
try {
URL url = new URL(urlString);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
return buffer.toString();
} finally {
if (reader != null)
reader.close();
}
}
class PhotoList extends AsyncTask<String, String, ArrayList<Photo>> {
#Override
// creating all user's photo without downloading
protected ArrayList<Photo> doInBackground(String... params) {
ArrayList<Photo> photos = new ArrayList<Photo>();
try {
JSONParser fp = new JSONParser();
JSONObject jo = (JSONObject) fp.parse(readUrl(params[0]));
JSONArray array = (JSONArray) jo.get("data");
for (int i = 0; i < array.size(); i++) {
JSONObject data = (JSONObject) array.get(i);
data.toString();
if (!data.isEmpty()) {
JSONObject images = (JSONObject) data.get("images");
JSONObject likes = (JSONObject) data.get("likes");
long like = (long) likes.get("count");
System.out.print(like);
JSONObject low = (JSONObject) images
.get("low_resolution");
JSONObject thumbnail = (JSONObject) images
.get("thumbnail");
JSONObject standart = (JSONObject) images
.get("standard_resolution");
photos.add(new Photo((String) low.get("url"),
(String) thumbnail.get("url"),
(String) standart.get("url"), like));
}
}
} catch (NetworkErrorException e) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),
"Ошибка в интернет соединении",
Toast.LENGTH_SHORT).show();
}
});
} catch (ParseException e) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),
"Неудалось загрузить страницу",
Toast.LENGTH_SHORT).show();
}
});
} catch (UnknownHostException e) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(
getApplicationContext(),
"Ошибка в интернет соединении, проверьте подключение к интернету",
Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
System.out.print(e.toString());
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),
"Неизвестная ошибка", Toast.LENGTH_SHORT)
.show();
}
});
}
return photos;
}
}
class MyTask extends AsyncTask<String, String, String> { // getting an id of
// the user
#Override
protected String doInBackground(String... params) {
String id = "";
try {
JSONParser fp = new JSONParser();
JSONObject jo = (JSONObject) fp.parse(readUrl(params[0]));
JSONObject data = (JSONObject) ((JSONArray) jo.get("data"))
.get(0);
if (!data.isEmpty()) {
id = (String) data.get("id");
} else {
Toast.makeText(getApplicationContext(),
"Логин не существует", Toast.LENGTH_SHORT).show();
return "";
}
} catch (NetworkErrorException e) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),
"Ошибка в интернет соединении",
Toast.LENGTH_SHORT).show();
}
});
} catch (ParseException e) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),
"Неудалось загрузить страницу",
Toast.LENGTH_SHORT).show();
}
});
} catch (UnknownHostException e) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(
getApplicationContext(),
"Ошибка в интернет соединении, проверьте подключение к интернету",
Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
System.out.print(e.toString());
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),
"Неизвестная ошибка", Toast.LENGTH_SHORT)
.show();
}
});
}
return id;
}
}
}
Photo_picker.java
package com.example.collage;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
public class Photo_picker extends Activity {
GridView gridview;
static ArrayList<Drawable> images;
public static void setViews(ArrayList<Drawable> images) {
Photo_picker.images = images;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo_picker);
gridview = (GridView) findViewById(R.id.gridView1_bir);
gridview.setAdapter(new ImageAdapter(this, images));
gridview.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE_MODAL);
gridview.setVerticalSpacing(4);
gridview.setHorizontalSpacing(4);
gridview.setBackgroundColor(Color.DKGRAY);
gridview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
view.setAlpha((float) 0.5);
}
});
}
public class ImageAdapter extends BaseAdapter implements ListAdapter {
private ArrayList<Drawable> images;
int height, width;
public ImageAdapter(Context context, ArrayList<Drawable> images) {
super();
this.images = images;
height = context.getResources().getDisplayMetrics().heightPixels;
width = context.getResources().getDisplayMetrics().widthPixels;
}
public int getCount() {
return images.size();
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(Photo_picker.this);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
imageView.setLayoutParams(new GridView.LayoutParams(
width / 2, height / 3));
} else {
imageView.setLayoutParams(new GridView.LayoutParams(
width / 3, height / 2));
}
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(0, 0, 0, 0);
imageView.setFocusable(false);
imageView.setFocusableInTouchMode(false);
imageView.setClickable(false);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageDrawable(images.get(position));
return imageView;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
}
}
Photo.java
package com.example.collage;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.ExecutionException;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
public class Photo implements Comparable<Photo> {
private URL lowimage, thumbnail, standart, url;
private long likes;
static int NUM_PHOTO = 20;
public Photo(String lowimage, String thumbnail, String standart, long likes) {
this.likes = likes;
try {
this.lowimage = new URL(lowimage);
this.thumbnail = new URL(thumbnail);
this.standart = new URL(standart);
} catch (MalformedURLException e) {
}
}
private static ArrayList<Photo> createPopularList(ArrayList<Photo> photo) {
ArrayList<Photo> popular;
popular = new ArrayList<Photo>();
Collections.sort(photo, Collections.reverseOrder());// descending order
if (photo.size() < NUM_PHOTO) {
popular.addAll(photo);
} else {
popular.addAll(photo.subList(0, NUM_PHOTO));
}
return popular;
}
public static ArrayList<Drawable> getDrawable(ArrayList<Photo> photo) {
Download d = new Download();
ArrayList<Drawable> list = new ArrayList<Drawable>();
try {
list = d.execute(createPopularList(photo)).get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
public URL getLowimage() {
return lowimage;
}
public URL getThumbnail() {
return thumbnail;
}
public URL getStandart() {
return standart;
}
public long getLikes() {
return likes;
}
#Override
public int compareTo(Photo another) {
return Long.compare(this.likes, another.getLikes());
}
static class Download
extends
AsyncTask<ArrayList<Photo>, ArrayList<Drawable>, ArrayList<Drawable>> {
#Override
protected ArrayList<Drawable> doInBackground(ArrayList<Photo>... params) {
ArrayList<Drawable> views = new ArrayList<Drawable>();
for (Photo p : params[0]) {
views.add(LoadImageFromURL(p.getLowimage()));
}
return views;
}
private Drawable LoadImageFromURL(URL url) {
try {
InputStream is = (InputStream) url.getContent();
Drawable d = Drawable.createFromStream(is, "src");
return d;
} catch (Exception e) {
System.out.println(e);
return null;
}
}
}
}
PhotoPicker xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:background="#e5e5e5"
>
<GridView
android:id="#+id/gridView1_bir"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginLeft="0dp"
android:columnWidth="160dp"
android:gravity="center"
android:horizontalSpacing="0dp"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="0dp" />
</RelativeLayout>
mainActivity.xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="132dp"
android:minWidth="200dip"
android:text="Давай коллаж" />
<EditText
android:id="#+id/editText1"
android:inputType="textVisiblePassword|textNoSuggestions"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginBottom="73dp"
android:ems="10" >
<requestFocus />
</EditText>
</RelativeLayout>
I have tried reading over the code briefly. I do not know why it would change 2 items (perhaps it is the view.setAlpha line). Maybe try using the position variable i.e.
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
images[position].setAlpha((float)0.5);
}
As I said, I just briefly read over the code. I hope this helps.

Related Links

Fixed dimension for cordova app
qt opengl es3 Offscreen render
Push notifications (GCM) permission at runtime?
Single Kotlin+libgdx codebase deployed to Android, desktop and browser?
How to make ImageView as large as possible
PagerAdapter with only one Fragment that is instantiate
Populate listview with a custom layout row with JSON data
Matching current Location with Database list of location with in 50 miles
Android PDF viewer - change page automatically
How to get Progressdialog while loading webpage for my code?
Custom animations for starting activities in Android not working as expected
Android Gradle detect is a release build or not in runtime?
IBM mfp push notifications in status bar (Cordova)
Enabling offline capabilities throws “java.lang.IllegalStateException: FirebaseApp with name [DEFAULT] doesn't exist.”
Pass PendingIntent Request Code To Put Extra
How to create/delete files in secondary storage SDCARD version after KitKat?

Categories

HOME
batch-file
awk
forms
fftw
solaris
cakephp-3.4
hpc
x264
joomla3.0
discrete-mathematics
fosrestbundle
dkim
text-mining
x-cart
libc
endpoint
favicon
dynatrace
screen-readers
android-7.0-nougat
google-picker
google-container-registry
pyramid
asp.net-core-webapi
lilypond
asciidoctor-pdf
googlebot
user-experience
named-entity-recognition
exploit
aggregation
monit
froala
pylons
paperjs
finagle
calculation
volatile
livelink
jmockit
catch-unit-test
linkedhashmap
contacts
vue-chartjs
pop3
html-encode
browser-extension
recurrent-neural-network
diacritics
css-position
numberpicker
softmax
chronicle-map
fwrite
reindex
template-toolkit
rxtx
vcloud-director-rest-api
gets
usart
mapxtreme
pacemaker
xcode-server
watch-os-2
pre-build-event
embedding
nss
bizagi
aurora
fuzzywuzzy
nio2
spring-retry
java-money
qt5.2
pax-exam
haskell-warp
dronekit-android
filesplitting
browserify-shim
wcm
gii
lambda-architecture
buffering
radiant
menubar
multiautocompletetextview
qscrollarea
rfc5322
android-usb
scriptaculous
windows-phone-8-sdk
ice-cube
ui-select2
flex++
server-administration
mapping-by-code
jquery-address
automationelement
nhprof
hbm2java
spread
business-model
commercial-application

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App