Putting data from a jsonobject into a gridview - java

i just wondering how to put values i retrieve from a json file, into a gridview, and then this gridview is in my custom adapter. at all times there will only be 6 id's which correspond to an image and 6 names in the gridview.
Here is my code;
private TextView tvData;
private ImageView imgtest;
String ChampionName;
String ChampionNameInLowerCase;
String item2;
String item3;
private ListView Championinfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listview = (ListView) findViewById(R.id.listView);
imgtest = (ImageView) findViewById(R.id.imageView);
// http://api.champion.gg/champion/Ekko/
new JSONTask().execute("http://api.champion.gg/champion/ekko/");
Championinfo = (ListView)findViewById(R.id.listView);
}
public class JSONTask extends AsyncTask<String, String, List<Layoutmodel>> {
#Override
protected List<Layoutmodel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONArray jsonarray = new JSONArray(finalJson);
List<Layoutmodel> LayoutModelList = new ArrayList<>();
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject finalObject = jsonarray.getJSONObject(i);
Layoutmodel layoutmodel = new Layoutmodel();
layoutmodel.setChampionName2(finalObject.getString("key"));
layoutmodel.setRole(finalObject.getString("role"));
ChampionName = finalObject.getString("key");
String role = finalObject.getString("role");
String items = finalObject.getString("items");
JSONObject ItemArray = new JSONObject(items);
item2 = ItemArray.getString("mostGames");
JSONObject ItemArray2 = new JSONObject(item2);
item3 = ItemArray2.getString("items");
JSONArray jsonarray2 = new JSONArray(item3);
StringBuffer TestBuffer = new StringBuffer();
List<Layoutmodel.itemname> itemlist = new ArrayList<>();
for (int j = 0; j < jsonarray2.length(); j++) {
JSONObject finalObject2 = jsonarray2.getJSONObject(j);
Integer ID = finalObject2.getInt("id");
String ItemName = finalObject2.getString("name");
TestBuffer.append(ID + "-" + ItemName + "\n");
Layoutmodel.itemname ItemNames = new Layoutmodel.itemname();
ItemNames.setName(ItemName);
}
layoutmodel.setItemnames(itemlist);
layoutmodel.setRole(role);
layoutmodel.setChampionName2(ChampionName);
LayoutModelList.add(layoutmodel);
return LayoutModelList;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<Layoutmodel> result) {
super.onPostExecute(result);
LayoutAdapter adapter2 = new LayoutAdapter(getApplicationContext(), R.layout.rows, result);
Championinfo.setAdapter(adapter2);
}
}
public class LayoutAdapter extends ArrayAdapter {
private List<Layoutmodel> LayoutModelList;
private int resource;
private LayoutInflater inflater;
public LayoutAdapter(Context context2, int resource, List<Layoutmodel> objects) {
super(context2, resource, objects);
LayoutModelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position2, View convertView2, ViewGroup parent2) {
if (convertView2 == null) {
convertView2 = inflater.inflate(R.layout.rows, null);
}
ImageView imageofchamp;
TextView nameofchamp;
TextView position;
GridView champitems;
// imageofchamp = (ImageView) convertView2.findViewById(R.id.imageView);
nameofchamp = (TextView) convertView2.findViewById(R.id.textView);
position = (TextView) convertView2.findViewById(R.id.smalltxt);
// champitems = (GridView) convertView2.findViewById(R.id.gridView);
nameofchamp.setText(LayoutModelList.get(position2).getChampionName2());
position.setText(LayoutModelList.get(position2).getRole());
return convertView2;
}
}
}
Here is what the code returns at the moment;
and here is the layout of the image above
and here is the code where i actually get the id and name of items from the json,
for (int j = 0; j < jsonarray2.length(); j++) {
JSONObject finalObject2 = jsonarray2.getJSONObject(j);
Integer ID = finalObject2.getInt("id");
String ItemName = finalObject2.getString("name");
TestBuffer.append(ID + "-" + ItemName + "\n");
Layoutmodel.itemname ItemNames = new Layoutmodel.itemname();
ItemNames.setName(ItemName);
}

To display all three roles, use a tabbed activity with fragments. Here is a pretty thorough, up to date tutorial on how to implement that. You already know how to pull the JSON data off your object, so you just have to do that 3 times, one for each role.

Related

How to update listview in for loop in asynk task

I'm reading some text from HttpUrlConnection request and putting it in ArrayList every iteration of a loop.
All works perfect, except items in ListView don't updating in UI after every iteration of a loop (only at the end).
I'm tried next 4 methods: arrayAdapter.notifyDataSetChanged(), listView.invalidateViews(), runOnUiThread(), onPostExecute() nothing helps.
Here is my code:
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayList<String> news = new ArrayList<>();
ArrayList<String> headers = new ArrayList<>();
ArrayAdapter<String> arrayAdapter;
static JSONArray array;
NewsUnpacker unpacker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
String link = "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty";
NewsLoader newsLoader = new NewsLoader();
array = null;
try {
array = newsLoader.execute(link).get();
} catch (Exception e) {
e.printStackTrace();
}
arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, headers);
listView.setAdapter(arrayAdapter);
final int size = 15;
for (int i = 0; i < size; i++) {
try {
unpacker = new NewsUnpacker(this);
String info = unpacker.execute("https://hacker-news.firebaseio.com/v0/item/" + array.get(i) + ".json?print=pretty").get();
if (info == null) {
unpacker.cancel(true);
return;
}
news.add(info);
headers.add(info.split(System.lineSeparator())[0]);
arrayAdapter.notifyDataSetChanged();
listView.invalidateViews();
unpacker.cancel(true);
} catch (Exception e) {
e.printStackTrace();
}
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
}
static class NewsUnpacker extends AsyncTask<String, Void, String> {
MainActivity activity;
NewsUnpacker(MainActivity activity) {
this.activity = activity;
}
#Override
protected String doInBackground(String... urls) {
String info = null;
try {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream is = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(is);
StringBuilder builder = new StringBuilder();
int data;
while ((data = reader.read()) != -1)
builder.append((char) data);
String title, urlParam;
JSONObject object = new JSONObject(builder.toString());
title = object.get("title").toString();
urlParam = object.get("url").toString();
info = title + System.lineSeparator() + urlParam;
System.out.println(info);
} catch (Exception e) {
e.printStackTrace();
}
return info;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
static class NewsLoader extends AsyncTask<String, Void, JSONArray> {
JSONArray array = null;
#Override
protected JSONArray doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream is = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(is);
StringBuilder builder = new StringBuilder();
int data;
while ((data = reader.read()) != -1)
builder.append((char) data);
array = new JSONArray(builder.toString());
} catch (Exception e) {
e.printStackTrace();
}
return array;
}
}
}

Unable to fetch images in Grid view

Main Activity:
public class MainActivity extends AppCompatActivity {
// ImageView iv;
public static StringBuffer finalparsedData;
public static GridView myGrid;
private static final String TAG = MainActivity.class.getSimpleName();
ArrayList<String> values = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myGrid=(GridView)findViewById(R.id.grid_view);
Button btnHit = (Button) findViewById(R.id.btnHit);
btnHit.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
new JSONTask().execute("https://api.flickr.com/services/rest/?method=flickr.photos.getRecent&" +
"api_key=46e71c8d2b35ba8c9c333a462ec8aea7&per_page=3&format=json&nojsoncallback=10");
}
});
values = new ArrayList<>();
}
/*static boolean isAirplaneModeOn(Context context) {
ContentResolver contentResolver = context.getContentResolver();
return Settings.System.getInt(contentResolver, AIRPLANE_MODE_ON, 0) != 0;
}*/
public class JSONTask extends AsyncTask<String, Void, String> {
String photoid;
int farm;
String server;
String secret;
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
StringBuffer buffer = null;
JSONArray parentarray = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
//JSONObject initialObject = new JSONObject("photos");
JSONObject initialObject = parentObject.getJSONObject("photos");
parentarray = initialObject.getJSONArray("photo");
finalparsedData = new StringBuffer();
for (int i = 0; i < parentarray.length(); i++) {
JSONObject finalObject = parentarray.getJSONObject(i);
photoid = finalObject.optString("id");
farm = finalObject.optInt("farm");
server = finalObject.optString("server");
secret = finalObject.optString("secret");
finalparsedData.append("https://farm" + farm + ".staticflickr.com/" + server + "/" + photoid+ "_" + secret + ".jpg" +"\n\n");
values.add(String.valueOf((finalparsedData)));
}
return "done";
} catch (MalformedURLException e) {
e.printStackTrace();
return "error";
} catch (IOException e) {
e.printStackTrace();
return "error";
} catch (JSONException e) {
e.printStackTrace();
return "error";
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
return "done";
}
} catch (IOException e) {
e.printStackTrace();
return "error";
}
}
}
#Override
protected void onPostExecute(String result) {
switch (result){
case "done":
MyImageAdapter adapter = new MyImageAdapter(MainActivity.this, values);
myGrid.setAdapter((ListAdapter) adapter);
break;
}
}
}
}
MyAdapterClass:
public class MyImageAdapter extends BaseAdapter {
ArrayList<String> values;
Context mContext;
public MyImageAdapter(Context mContext, ArrayList<String> values) {
this.values = values;
this.mContext = mContext;
}
#Override
public int getCount() {
return values.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder;
;
if (row == null){
LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.grid,parent,false);
holder = new ViewHolder();
holder.imageView = (ImageView) row.findViewById(R.id.image_View);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
String image = values.get(position);
Picasso.with(mContext).load(image).into(holder.imageView);
return row;
}
public class ViewHolder {
ImageView imageView;
}
}
I got a problem during images loading in gridview, out of 10 images only 1 image is shown and rest of them showing "this images is no longer available"
Hahaha, silly mistake. Just replace your for loop inside JSONTask with this,
.
.
.
for (int i = 0; i < parentarray.length(); i++) {
JSONObject finalObject = parentarray.getJSONObject(i);
photoid = finalObject.optString("id");
farm = finalObject.optInt("farm");
server = finalObject.optString("server");
secret = finalObject.optString("secret");
String fullPath = "https://farm" + farm + ".staticflickr.com/" + server + "/" + photoid+ "_" + secret + ".jpg";
values.add(fullPath);
}
.
.
.
No need to use StringBuffer. You should use normal String variable. :)

RecyclerView shows the same items

I am trying to implement RecyclerView, showing the data from JSONArray. Parsing works perfect, but RecyclerView shows in every item the information that must be only in the last item. There is the screenshot to make it clear.
Here is my code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.AppTheme);
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
new parseTask().execute();
}
private class parseTask extends AsyncTask<Void, Void, String> {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String resultJson = "";
ProgressDialog pdLoading = new ProgressDialog(MainActivity.this, R.style.MyDialogStyle);
#Override
protected void onPreExecute() {
super.onPreExecute();
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL("http://songo.eu.pn/db_GetFromSongs.php");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
resultJson = buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
return resultJson;
}
#Override
protected void onPostExecute(String strJson) {
super.onPostExecute(strJson);
List<DataSongs> data = new ArrayList<>();
JSONObject dataJsonObj = null;
try {
dataJsonObj = new JSONObject(strJson);
JSONArray songs = dataJsonObj.getJSONArray("Songs");
DataSongs songData = new DataSongs();
for (int i = 0; i < songs.length(); i++) {
JSONObject song = songs.getJSONObject(i);
songData.songName = song.getString("song");
songData.songGenreID = song.getString("GenreID");
songData.songUserID = song.getString("UserID");
data.add(songData);
Log.e("songo", "SongName: " + data.get(i).songName);
}
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mAdapter = new RecyclerAdapter(MainActivity.this, data, mRecyclerView);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(MainActivity.this);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setLayoutManager(mLayoutManager);
} catch (JSONException e) {
e.printStackTrace();
}
pdLoading.dismiss();
}
}
RecyclerAdapter.java
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private Context context;
private LayoutInflater inflater;
List<DataSongs> data = Collections.emptyList();
public RecyclerAdapter(Context context, List<DataSongs> data, RecyclerView recyclerView) {
this.context = context;
inflater = LayoutInflater.from(context);
this.data = data;
this.recyclerView = recyclerView;
}
class ViewHolder extends RecyclerView.ViewHolder{
TextView tv_songName;
TextView tv_songGenreID;
TextView tv_songUserID;
public ViewHolder(View itemView) {
super(itemView);
tv_songName = (TextView) itemView.findViewById(R.id.tv_songName);
tv_songGenreID = (TextView) itemView.findViewById(R.id.tv_songGenreID);
tv_songUserID = (TextView) itemView.findViewById(R.id.tv_songUserID);
}
}
// Создает новые views (вызывается layout manager-ом)
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v=inflater.inflate(R.layout.recycler_item, parent,false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
DataSongs current = data.get(position);
holder.tv_songName.setText(current.songName);
holder.tv_songGenreID.setText(current.songGenreID);
holder.tv_songUserID.setText(current.songUserID);
Log.e("songo", "SongName: " + data.get(position).songName);
}
#Override
public int getItemCount() {
return data.size();
}
Log from MainActivity shows information as it should be (no equal lines).
Log from RecyclerAdapter shows that every songName is the same.
You are overriding the same DataSongs instance every iteration.
DataSongs songData = new DataSongs();
for (int i = 0; i < songs.length(); i++) {
JSONObject song = songs.getJSONObject(i);
songData.songName = song.getString("song");
songData.songGenreID = song.getString("GenreID");
songData.songUserID = song.getString("UserID");
data.add(songData);
Log.e("songo", "SongName: " + data.get(i).songName);
}
Note that the new keyword is only called once.
The resulting list will contain the same object multiple times, and it's attributes are set to the last song in the list.
Simply move the creation of songData inside of the loop
for (int i = 0; i < songs.length(); i++) {
JSONObject song = songs.getJSONObject(i);
DataSongs songData = new DataSongs();
songData.songName = song.getString("song");
songData.songGenreID = song.getString("GenreID");
songData.songUserID = song.getString("UserID");
data.add(songData);
Log.e("songo", "SongName: " + data.get(i).songName);
}
dataJsonObj = new JSONObject(strJson);
JSONArray songs = dataJsonObj.getJSONArray("Songs");
DataSongs songData = new DataSongs();
for (int i = 0; i < songs.length(); i++) {
JSONObject song = songs.getJSONObject(i);
songData.songName = song.getString("song");
songData.songGenreID = song.getString("GenreID");
songData.songUserID = song.getString("UserID");
data.add(songData);
Log.e("songo", "SongName: " + data.get(i).songName);
}
The problem is not in RecyclerView related, it's in creating object .DataSongs object has been created only once , you have to create it every time you receive data from JSON array.So,create it inside for loop :
dataJsonObj = new JSONObject(strJson);
JSONArray songs = dataJsonObj.getJSONArray("Songs");
for (int i = 0; i < songs.length(); i++) {
JSONObject song = songs.getJSONObject(i);
DataSongs songData = new DataSongs();
songData.songName = song.getString("song");
songData.songGenreID = song.getString("GenreID");
songData.songUserID = song.getString("UserID");
data.add(songData);
Log.e("songo", "SongName: " + data.get(i).songName);
}
DataSongs songData = new DataSongs();
This line of code inside your for loop you need to create new json object each time to solve this issue
Try this
try {
dataJsonObj = new JSONObject(strJson);
JSONArray songs = dataJsonObj.getJSONArray("Songs");
DataSongs songData = null;
for (int i = 0; i < songs.length(); i++) {
songData = new DataSongs();
JSONObject song = songs.getJSONObject(i);
songData.songName = song.getString("song");
songData.songGenreID = song.getString("GenreID");
songData.songUserID = song.getString("UserID");
data.add(songData);
Log.e("songo", "SongName: " + data.get(i).songName);
}
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mAdapter = new RecyclerAdapter(MainActivity.this, data, mRecyclerView);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(MainActivity.this);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setLayoutManager(mLayoutManager);
} catch (JSONException e) {
e.printStackTrace();
}
You were creating the object outside the loop, as a result, there was only one object created
public class MainActivity extends AppCompatActivity {
RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.AppTheme);
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
new parseTask().execute();
}
private class parseTask extends AsyncTask<Void, Void, String> {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String resultJson = "";
ProgressDialog pdLoading = new ProgressDialog(MainActivity.this, R.style.MyDialogStyle);
#Override
protected void onPreExecute() {
super.onPreExecute();
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL("http://songo.eu.pn/db_GetFromSongs.php");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
resultJson = buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
return resultJson;
}
#Override
protected void onPostExecute(String strJson) {
super.onPostExecute(strJson);
List<DataSongs> data = new ArrayList<>();
JSONObject dataJsonObj = null;
try {
dataJsonObj = new JSONObject(strJson);
JSONArray songs = dataJsonObj.getJSONArray("Songs");
for (int i = 0; i < songs.length(); i++) {
JSONObject song = songs.getJSONObject(i);
/**
* you were wrong here
*/
DataSongs songData = new DataSongs();
songData.songName = song.getString("song");
songData.songGenreID = song.getString("GenreID");
songData.songUserID = song.getString("UserID");
data.add(songData);
Log.e("songo", "SongName: " + data.get(i).songName);
}
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mAdapter = new RecyclerAdapter(MainActivity.this, data, mRecyclerView);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(MainActivity.this);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setLayoutManager(mLayoutManager);
} catch (JSONException e) {
e.printStackTrace();
}
pdLoading.dismiss();
}
}

I am not able to get the gridview populated with textview in Android Fragment

i am not able to populate the imageview textview inside gridview using fragments.
It is showing blank intead of gridview populating in my project can please anyone see the code below and let me know what i have to change
And the populating the image and text is from the mysql database dynamically
public class StoreHomeFragment extends Fragment {
final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.store_home, container, false);
final GridView gridView1 = (GridView)rootView.findViewById(R.id.store_home_gridview);
gridView1.setAdapter(new ImageAdapter(rootView.getContext(), MyArrList));
return rootView;
}
//Activity is created
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String url = "http://192.168.1.132/Android/App/good.php"; //url where i am using select query and retrieving it from database
try {
JSONArray data = new JSONArray(getJSONUrl(url));
HashMap<String, String> map;
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);//retrieving from db
map = new HashMap<String, String>();
map.put("name", c.getString("name"));
map.put("artist", c.getString("artist"));
map.put("price", c.getString("price"));
map.put("image", c.getString("image"));
MyArrList.add(map);
}
//gridView1.setAdapter(new ImageAdapter(this,MyArrList));
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
//I have used imageAdapter
class ImageAdapter extends BaseAdapter
{
private Context context;
public ImageView imageView;
private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String, String>>();
public ImageAdapter(Context c,ArrayList<HashMap<String, String>> list)
{
context = c;
MyArr = list;
}
public int getCount() {
return MyArr.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.store_home_gridview_row, null);
}
TextView tv_title = (TextView) convertView.findViewById(R.id.textview_name);
tv_title.setText("Title:"+MyArr.get(position).get("name"));
TextView tv_artist = (TextView) convertView.findViewById(R.id.textview_artist);
tv_artist.setText("Artist:"+MyArr.get(position).get("artist"));
TextView tv_duration = (TextView) convertView.findViewById(R.id.textview_price);
tv_duration.setText("Price:"+MyArr.get(position).get("price"));
String abc = (MyArr.get(position).get("image"));
String abcd = "http://192.168.1.132/images/products/"+abc;
imageView = (ImageView) convertView.findViewById(R.id.imageView1);
try
{
URL url3 = null;
try {
url3 = new URL(abcd);
} catch (Exception e) {
e.printStackTrace();
}
Bitmap bmp = BitmapFactory.decodeStream(url3.openConnection().getInputStream()); //image is populated
imageView.setImageBitmap(bmp);
}
catch(Exception par)
{
imageView.setImageResource(android.R.drawable.ic_menu_report_image);
}
return convertView;
}
}
/*** Get JSON Code from URL ***/
public String getJSONUrl(String url) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try
{
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
System.out.println ( "status Code : " + statusCode );
if (statusCode == 200)
{
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null)
{
str.append(line);
}
}
else
{
Log.e("Log", "Failed to download file..");
}
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println ( "str : " + str.toString() );
return str.toString();
}
}
Follow the steps Hope this helps you
1) Remove these lines from onCreateView() method
final GridView gridView1 = (GridView)rootView.findViewById(R.id.store_home_gridview);
gridView1.setAdapter(new ImageAdapter(rootView.getContext(), MyArrList));
2)Modify onActivityCreated() as follow
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
String url = "http://192.168.1.132/Android/App/good.php";
try {
JSONArray data = new JSONArray(getJSONUrl(url));
HashMap<String, String> map;
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("name", c.getString("name"));
map.put("artist", c.getString("artist"));
map.put("price", c.getString("price"));
map.put("image", c.getString("image"));
MyArrList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
final GridView gridView1 = (GridView) rootView.findViewById(R.id.store_home_gridview);
gridView1.setAdapter(new ImageAdapter(getActivity(), MyArrList));
}
}.execute();
}

Android spinner with objects

I have an async task which populates a spinner with data. The spinner data comes from objects in a list. My problem is when I set the onclick listener for the items in the list I also want the id from the object not just the name:
public class PortfolioGetAllLists extends AsyncTask<String, Void, String> {
Context c;
PortfolioGetAllBeers.OnArticleSelectedListener useThis;
private ProgressDialog Dialog;
public PortfolioGetAllLists (Context context, PortfolioGetAllBeers.OnArticleSelectedListener thisListener)
{
c = context;
useThis = thisListener;
Dialog = new ProgressDialog(c);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPreExecute() {
Dialog.setMessage("Getting Brewery List");
Dialog.setTitle("Loading");
Dialog.setCancelable(false);
Dialog.show();
}
protected void onPostExecute(String result){
//decode json here
try{
JSONArray jsonArray = new JSONArray(result);
//acces listview
final ListView lv = (ListView) ((Activity) c).findViewById(R.id.allYourBeersList);
//make array list for beer
final List<String> tasteList = new ArrayList<String>();
tasteList.add("");
for(int i = 0; i < jsonArray.length(); i++) {
String bID = jsonArray.getJSONObject(i).getString("id");
String beer = jsonArray.getJSONObject(i).getString("name");
String rate = "na";
String beerID = "na";
//create object
ShortBeerInfo tempTaste = new ShortBeerInfo(beer, rate, beerID, bID);
//add to arraylist
tasteList.add(beer);
}
// Selection of the spinner
Spinner spinner = (Spinner) ((Activity) c).findViewById(R.id.portfolioSpinner2);
// Application of the Array to the Spinner
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(c, android.R.layout.simple_spinner_item,tasteList );
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
spinner.setAdapter(spinnerArrayAdapter);
//add on item selected
final Spinner portfolioType = (Spinner) ((Activity) c).findViewById(R.id.portfolioSpinner2);
portfolioType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String portfolioChoice = portfolioType.getSelectedItem().toString();
//Toast.makeText(((Activity) c).getApplicationContext(), portfolioChoice, Toast.LENGTH_LONG).show();
lv.setAdapter(null);
//get brewery beers
//get userID
//get user data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
String userID = prefs.getString("userID", null);
try {
portfolioChoice = URLEncoder.encode(portfolioChoice, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//construct url
String url = "myURL";
Log.d("portfolio", url);
//async task goes here
//new PortfolioGetAllBeers(selectedItemView.getContext()).execute(url);
PortfolioGetAllBeers task = new PortfolioGetAllBeers(c);
task.setOnArticleSelectedListener(useThis);
task.execute(url);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// do nothing
}
});
}
catch(Exception e){
}
Dialog.dismiss();
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
}
This line below is the line which get the beers name, but I do not know how to get also the id from the object which sets the listview name:
String portfolioChoice = portfolioType.getSelectedItem().toString();
Update:
I have changed my above code to this to incorporate a custom adapter:
public class PortfolioGetAllLists extends AsyncTask<String, Void, String> {
Context c;
PortfolioGetAllBeers.OnArticleSelectedListener useThis;
private ProgressDialog Dialog;
public PortfolioGetAllLists (Context context, PortfolioGetAllBeers.OnArticleSelectedListener thisListener)
{
c = context;
useThis = thisListener;
Dialog = new ProgressDialog(c);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPreExecute() {
Dialog.setMessage("Getting Brewery List");
Dialog.setTitle("Loading");
Dialog.setCancelable(false);
Dialog.show();
}
protected void onPostExecute(String result){
//decode json here
try{
JSONArray jsonArray = new JSONArray(result);
//acces listview
final ListView lv = (ListView) ((Activity) c).findViewById(R.id.allYourBeersList);
//make array list for beer
final List<ShortBeerInfo> tasteList = new ArrayList<ShortBeerInfo>();
//tasteList.add("");
for(int i = 0; i < jsonArray.length(); i++) {
String bID = jsonArray.getJSONObject(i).getString("id");
String beer = jsonArray.getJSONObject(i).getString("name");
String rate = "na";
String beerID = "na";
//create object
ShortBeerInfo tempTaste = new ShortBeerInfo(beer, rate, beerID, bID);
//add to arraylist
tasteList.add(tempTaste);
}
// Selection of the spinner
Spinner spinner = (Spinner) ((Activity) c).findViewById(R.id.portfolioSpinner2);
// Application of the Array to the Spinner
ShortBeerInfoAdapter<ShortBeerInfo> spinnerArrayAdapter = new ArrayAdapter<ShortBeerInfo>(c, android.R.layout.simple_spinner_item,tasteList );
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
spinner.setAdapter(spinnerArrayAdapter);
//add on item selected
final Spinner portfolioType = (Spinner) ((Activity) c).findViewById(R.id.portfolioSpinner2);
portfolioType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String portfolioChoice = portfolioType.getSelectedItem().toString();
//Toast.makeText(((Activity) c).getApplicationContext(), portfolioChoice, Toast.LENGTH_LONG).show();
lv.setAdapter(null);
//get brewery beers
//get userID
//get user data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
String userID = prefs.getString("userID", null);
try {
portfolioChoice = URLEncoder.encode(portfolioChoice, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//construct url
String url = "myURL";
Log.d("portfolio", url);
//async task goes here
//new PortfolioGetAllBeers(selectedItemView.getContext()).execute(url);
PortfolioGetAllBeers task = new PortfolioGetAllBeers(c);
task.setOnArticleSelectedListener(useThis);
task.execute(url);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// do nothing
}
});
}
catch(Exception e){
}
Dialog.dismiss();
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
}
but on this line:
ShortBeerInfoAdapter<ShortBeerInfo> spinnerArrayAdapter = new ArrayAdapter<ShortBeerInfo>(c, android.R.layout.simple_spinner_item,tasteList );
I am getting shortbeerinfoadapter does not have type parameters
my short beer info adapter is:
public class ShortBeerInfoAdapter extends ArrayAdapter<ShortBeerInfo> {
Context context;
int layoutResourceId;
List<ShortBeerInfo> data = null;
public ShortBeerInfoAdapter(Context context, int layoutResourceId, List<ShortBeerInfo> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
beerHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new beerHolder();
holder.txtBeer = (TextView)row.findViewById(R.id.breweryName);
holder.txtRate = (TextView)row.findViewById(R.id.breweryRate);
holder.txtBar = (RatingBar) row.findViewById(R.id.starbar);
row.setTag(holder);
}
else
{
holder = (beerHolder)row.getTag();
}
ShortBeerInfo beer = data.get(position);
holder.txtBeer.setText(beer.beer);
holder.txtRate.setText(beer.rate + " out of 5.00 Stars");
holder.numHolder= Float.parseFloat(beer.rate);
holder.txtBar.setNumStars(5);
holder.txtBar.setRating(holder.numHolder);
return row;
}
static class beerHolder
{
TextView txtBeer;
TextView txtRate;
RatingBar txtBar;
Float numHolder;
}
}
You have your ShortBeerInfo, which includes the name and ID. You take the beer name, add it to a list of strings, then create the ArrayAdapter from that list. The ArrayAdapter only contains the names.
To get the ID you will need a custom array adapter of type ShortBeerInfo. You'll need to override OnCreateView in the adapter to create the View object for the list item that only contains the beer name. (Or any other beer info you may want to display)
Then in your selection listener getSelectedItem will return a ShortBeerInfo, containing the ID of the selected beer.

Categories