addView is not displaying the items - android

I am trying to fetch JSON object from an Api and display it on a checkList on a LinearLayout. Even though I am adding the checklist View to the container it is not showing. Is it the case that I have to use notifyDataSetChanged(), If so how can I implement it in LinearLayout.
Thank you . I do apologize for my english.
public class NasilYapilir extends Fragment {
int index;
private CheckBox checkBox;
private CheckBox[] checkBoxes;
List<Reciep> reciepList = new ArrayList<>();
LinearLayout linearLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_nasil_yapilir, container, false);
index = getArguments().getInt(DetailViewPager.KEY_INDEX_TAG);
load_data(index);
linearLayout = (LinearLayout) view.findViewById(R.id.linearLayout);
checkBoxes = new CheckBox[reciepList.size()];
populateDirections(reciepList,linearLayout);
Log.i("we are in nasil yaplir",index + "");
return view;
}
public void populateDirections(List<Reciep> reciep, ViewGroup container){
int i = 0;
for(Reciep recieps : reciep){
checkBoxes[i] = new CheckBox(getActivity());
// checkBoxes[i].setPadding(8,16,8,16);
checkBoxes[i].setText(recieps.getQuantity()+ " "+ recieps.getUnit_ad()+ " "+ recieps.getIngredients_ad());
reciep.size();
container.addView(checkBoxes[i]);
i++;
}
}
public void load_data(int index) {
task.execute("http://yemekapp.kuarkdijital.com.tr/v_recipe.php?id=" + index);
}
AsyncTask<String, Void, String> task = new AsyncTask<String, Void, String>() {
#Override
protected String doInBackground(String... params) {
URL url;
HttpURLConnection URLConnection = null;
String current = "";
try {
url = new URL(params[0]);
URLConnection = (HttpURLConnection) url.openConnection();
URLConnection.connect();
InputStream inputStream = URLConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while (data != -1) {
current += (char) data;
data = reader.read();
}
JSONObject itemObject = null;
JSONObject quantityObject = null;
// JSONObject popularObject = null;
JSONObject jsonObject = new JSONObject(current);
String item = jsonObject.getString("item");
JSONArray itemArray = new JSONArray(item);
// JSONArray popularArray = new JSONArray(popular);
for (int i = 0; i < itemArray.length(); i++) {
itemObject = itemArray.getJSONObject(i);
String itemsQuantity = itemObject.getString("items");
JSONArray quantityArray = new JSONArray(itemsQuantity);
for(int j = 0; j<quantityArray.length() ;j++){
quantityObject = quantityArray.getJSONObject(i);
Reciep reciep = new Reciep(quantityObject.getString("Quantity"),quantityObject.getString("unit_ad"),quantityObject.getString("ingredient_ad"));
reciepList.add(reciep);
Log.i("quatityArray",quantityArray.get(j).toString());
}
// popularObject = popularArray.getJSONObject(i);
// DailyData DailyData = new DailyData(dailyObject.getInt("id"), dailyObject.getString("Servings"), dailyObject.getString("Title"), dailyObject.getString("CookTime"), dailyObject.getString("Image"));
// DailyData PopularData = new DailyData(popularObject.getInt("id"), popularObject.getString("Servings"), popularObject.getString("Title"), popularObject.getString("CookTime"), popularObject.getString("Image"));
// daily_data_list.add(DailyData);
// popular_data_list.add(PopularData);
}
}
catch (JSONException e) {
e.printStackTrace();
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return current;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// notifyDataSetChanged();
}
};
}

Try this code
public class NasilYapilir extends Fragment {
int index;
private CheckBox checkBox;
private CheckBox[] checkBoxes;
List<Reciep> reciepList = new ArrayList<>();
LinearLayout linearLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_nasil_yapilir, container, false);
index = getArguments().getInt(DetailViewPager.KEY_INDEX_TAG);
linearLayout = (LinearLayout) view.findViewById(R.id.linearLayout);
checkBoxes = new CheckBox[reciepList.size()];
load_data(index);
//populateDirections(reciepList,linearLayout);
Log.i("we are in nasil yaplir",index + "");
return view;
}
public void populateDirections(List<Reciep> reciep, ViewGroup container){
int i = 0;
for(Reciep recieps : reciep){
checkBoxes[i] = new CheckBox(getActivity());
// checkBoxes[i].setPadding(8,16,8,16);
checkBoxes[i].setText(recieps.getQuantity()+ " "+
recieps.getUnit_ad()+ " "+ recieps.getIngredients_ad());
reciep.size();
container.addView(checkBoxes[i]);
i++;
}
}
public void load_data(int index) {
task.execute("http://yemekapp.kuarkdijital.com.tr/v_recipe.php?id=" + index);
}
AsyncTask<String, Void, String> task = new AsyncTask<String, Void, String>() {
#Override
protected String doInBackground(String... params) {
URL url;
HttpURLConnection URLConnection = null;
String current = "";
try {
url = new URL(params[0]);
URLConnection = (HttpURLConnection) url.openConnection();
URLConnection.connect();
InputStream inputStream = URLConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while (data != -1) {
current += (char) data;
data = reader.read();
}
}
catch (JSONException e) {
e.printStackTrace();
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return current;
}
#Override
protected void onPostExecute(String current) {
super.onPostExecute(current);
if(current.isEmpty())
return;
JSONObject itemObject = null;
JSONObject quantityObject = null;
JSONObject jsonObject = new JSONObject(current);
String item = jsonObject.getString("item");
JSONArray itemArray = new JSONArray(item);
for (int i = 0; i < itemArray.length(); i++) {
itemObject = itemArray.getJSONObject(i);
String itemsQuantity = itemObject.getString("items");
JSONArray quantityArray = new JSONArray(itemsQuantity);
for(int j = 0; j<quantityArray.length() ;j++){
quantityObject = quantityArray.getJSONObject(i);
Reciep reciep = new Reciep(quantityObject.getString("Quantity"),quantityObject.getString("unit_ad"),quantityObject.getString("ingredient_ad"));
reciepList.add(reciep);
Log.i("quatityArray",quantityArray.get(j).toString());
}
}
populateDirections(reciepList,linearLayout);
}
}
}

Related

AsyncTask + JSON parsing to Listview only sometimes shows data

Sometimes it shows data, sometimes it shows nothing.
public class HomeFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.home_fragment, container, false);
arraylist1 = new ArrayList<>();
listOfNews = (ListView) view.findViewById(R.id.listView);
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute("url");
}
});
return view;
}
public class ReadJSON extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... url) {
String st = readURL(url[0]);
Log.d("st", st);
return st;
}
#Override
protected void onPostExecute(String content) {
try {
JSONObject jsonObject = new JSONObject(content);
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
Log.d(i+":jsonArray object", jsonArray.toString() + " size= " + jsonArray.length());
JSONObject productObject = jsonArray.getJSONObject(i);
JSONObject img = productObject.getJSONObject("image");
JSONObject da = img.getJSONObject("data");
arraylist1.add(new HotNews(
da.getString("filename"),
productObject.getString("title"),
productObject.getString("article_by"),
productObject.getString("date_publish"),
productObject.getString("short_description")
));
}
Log.d("jsonArray news list1", arraylist1.size() + "");
} catch (JSONException e) {
e.printStackTrace();
}
adapter = new ListViewAdapter(view.getContext(), R.layout.list_view_adapter, arraylist1);
listOfNews.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
private static String readURL(String theUrl) {
StringBuilder content = new StringBuilder();
try {
//create url object
URL url = new URL(theUrl);
//create url connection
URLConnection urlConnection = url.openConnection();
//wrap the urlconnection in a bufferedreader
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
content.append(line + "\n");
}
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
return content.toString();
}
}
public class ListViewAdapter extends ArrayAdapter<HotNews> {
public ListViewAdapter(Context context, int resource, ArrayList<HotNews> arrayList) {
super(context, resource,arrayList);
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.arrayList = arrayList;
this.context = context;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
v = mInflater.inflate(R.layout.list_view_adapter, parent, false);
}
image = (ImageView) v.findViewById(R.id.imagetitle);
title = (TextView) v.findViewById(R.id.txtTitle);
doer = (TextView) v.findViewById(R.id.doer);
date = (TextView) v.findViewById(R.id.txtdate);
text = (TextView) v.findViewById(R.id.text);
final HotNews news = getItem(position);
Picasso.with(getContext()).load("url" + news.getImage()).noFade().into(image);
title.setText(news.getTitle());
doer.setText(news.getDoer());
date.setText(news.getDate());
text.setText(news.getContent());
return v;
}
}
try this code :
public class HomeFragment extends Fragment {
private View view;
private ArrayList<HotNews> arraylist1;
private ListView listOfNews;
private int SUCCESS = 1;
private int FAILS = 0;
private int NO_DATA = 2;
private int ERROR = -1;
private ListViewAdapter adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.home_fragment, container, false);
arraylist1 = new ArrayList<>();
listOfNews = (ListView) view.findViewById(R.id.listView);
adapter = new ListViewAdapter();
listOfNews.setAdapter(adapter);
new ReadJSON().execute("url");
return view;
}
public class ReadJSON extends AsyncTask<String, Integer, Integer> {
#Override
protected Integer doInBackground(String... url) {
String response = readURL(url[0]);
Log.d("response ", response);
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("data");
arraylist1.clear();
if(jsonArray.length()>0) {
for (int i = 0; i < jsonArray.length(); i++) {
Log.d(i + ":jsonArray object", jsonArray.toString() + " size= " + jsonArray.length());
JSONObject productObject = jsonArray.getJSONObject(i);
JSONObject img = productObject.getJSONObject("image");
JSONObject da = img.getJSONObject("data");
arraylist1.add(new HotNews(
da.getString("filename"),
productObject.getString("title"),
productObject.getString("article_by"),
productObject.getString("date_publish"),
productObject.getString("short_description")
));
}
}else{
return NO_DATA;
}
Log.d("jsonArray news list1", arraylist1.size() + "");
} catch (Exception e) {
e.printStackTrace();
return ERROR;
}
return SUCCESS;
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
Log.d("parseResponse", integer + "");
if(integer==SUCCESS){
adapter.notifyDataSetChanged();
}else if(integer==ERROR){
Toast.makeText(getActivity(),"Server or Exception Error!", Toast.LENGTH_SHORT).show();
}else if(integer==NO_DATA){
Toast.makeText(getActivity(),"No Data!", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getActivity(),"Some thing went wrong!", Toast.LENGTH_SHORT).show();
}
}
}
class ListViewAdapter extends BaseAdapter{
#Override
public int getCount() {
return arraylist1.size();
}
#Override
public Object getItem(int position) {
return arraylist1.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ListViewHolder holder;
if (v == null) {
v = LayoutInflater.from(getActivity()).inflate(R.layout.list_view_adapter, parent, false);
holder = new ListViewHolder(v);
v.setTag(holder);
}else{
holder = (ListViewHolder)v.getTag();
}
final HotNews news = arraylist1.get(position);
holder.title.setText(news.getTitle());
holder.doer.setText(news.getDoer());
holder.date.setText(news.getDate());
holder.text.setText(news.getContent());
Picasso.with(getContext()).load("url" + news.getImage()).noFade().into(holder.image);
return v;
}
class ListViewHolder {
private ImageView image;
private TextView title,doer,date,text;
public ListViewHolder(View v){
image = (ImageView) v.findViewById(R.id.imagetitle);
title = (TextView) v.findViewById(R.id.txtTitle);
doer = (TextView) v.findViewById(R.id.doer);
date = (TextView) v.findViewById(R.id.txtdate);
text = (TextView) v.findViewById(R.id.text);
}
}
}
private static String readURL(String theUrl) {
StringBuilder content = new StringBuilder();
try {
//create url object
URL url = new URL(theUrl);
//create url connection
URLConnection urlConnection = url.openConnection();
//wrap the urlconnection in a bufferedreader
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
content.append(line + "\n");
}
bufferedReader.close();
}
catch (Exception e) {
e.printStackTrace();
}
return content.toString();
}
}
You are seeing this error, which is crashing the entire loop. You may be requesting 10 objects, but at the first object without that image attribute, it is exiting.
W/System.err: org.json.JSONException: No value for image
So, recommendation (other than using Retrofit to manage your JSON API's) would be to use the optType() methods rather than the getType() methods of the JSON objects.
For example,
JSONObject img = productObject.optJSONObject("image");
This will set img to null when the "image" attribute does not exist.
Just be aware of that later in case you have a NullPointerException when trying to use img on this line
JSONObject da = img.getJSONObject("data");

How to parse JSON dat with HTTP Post method in android studio

JSONParser.class
package com.example.diptiagravat.myapplication;
public class JSONParser {
public String getJSON(String url, int timeout) {
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
return null;
}
public String sendHTTPData(String urlpath, String id) {
HttpURLConnection connection = null;
try {
URL url=new URL(urlpath);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
OutputStreamWriter streamWriter = new OutputStreamWriter(connection.getOutputStream());
streamWriter.write(id);
streamWriter.flush();
StringBuilder stringBuilder = new StringBuilder();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK){
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(streamReader);
String response = null;
while ((response = bufferedReader.readLine()) != null) {
stringBuilder.append(response + "\n");
}
bufferedReader.close();
Log.d("test", stringBuilder.toString());
return stringBuilder.toString();
} else {
Log.e("test", connection.getResponseMessage());
return null;
}
} catch (Exception exception){
Log.e("test", exception.toString());
return null;
} finally {
if (connection != null){
connection.disconnect();
}
}
}
}
MainActivity.java
package com.example.diptiagravat.myapplication;
public class MainActivity extends AppCompatActivity {
private TextView txtid, txtcname;
Spinner spcnt, spstate;
public ArrayList<String> clist;
ArrayAdapter<String> cad;
public ArrayList<String> slist;
ArrayAdapter<String> sad;
public String strcnt;
private static String url = "http://urmiinfotech.com/demo/ifirst/app_api/get_country_list.php";
private static String stateUrl = "http://urmiinfotech.com/demo/ifirst/app_api/get_state_list.php";
private static final String TAG_USER = "country";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "country_name";
private ArrayList<Country> clistModels;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
CountryAsyncTask countryAsyncTask= new CountryAsyncTask();
countryAsyncTask.execute();
}
private void initViews() {
txtid = (TextView) findViewById(R.id.tvid);
txtcname = (TextView) findViewById(R.id.tvcname);
spcnt = (Spinner) findViewById(R.id.spcnt);
spstate = (Spinner) findViewById(R.id.spstate);
clist = new ArrayList<String>();
slist = new ArrayList<String>();
}
public class CountryAsyncTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = null;
try {
json = new JSONObject(jParser.getJSON(url, 5000));
} catch (JSONException e) {
e.printStackTrace();
}
return json.toString();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.i("Result Ravi", result);
try {
JSONObject obj = new JSONObject(result);
JSONArray cntArray = obj.getJSONArray("country");
if (cntArray.length() > 0) {
for (int i = 0; i < cntArray.length(); i++) {
final JSONObject temp = cntArray.getJSONObject(i);
// txtid.setText(temp.getString("id"));
// txtcname.setText(temp.getString("country_name"));
Country country = new Gson().fromJson(temp.toString(), Country.class);
clist = new ArrayList<String>();
clistModels = new ArrayList<Country>();
clistModels.add(new Country(temp.optString("id"), temp.optString("country_name"), "", null));
clist.add(temp.getString("country_name"));
cad = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, clist);
spcnt.setAdapter(cad);
spcnt.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
strcnt = clistModels.get(position).getId();
//strcnt = parent.getItemAtPosition(position).toString();
Log.i("id", strcnt);
new StatesAsyncTask().execute();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// txtid.setText(temp.getString(country.getId()));
// txtcname.setText(temp.getString(country.getCountryName()));
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class StatesAsyncTask extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = null;
try {
json = new JSONObject(jParser.sendHTTPData(stateUrl, strcnt));
} catch (JSONException e) {
e.printStackTrace();
}
return json.toString();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject obj = new JSONObject(s);
JSONArray stArray = obj.getJSONArray("statelist");
if (stArray.length() > 0) {
for (int i = 0; i < stArray.length(); i++) {
final JSONObject temp = stArray.getJSONObject(i);
// txtid.setText(temp.getString("id"));
// txtcname.setText(temp.getString("country_name"));
Statelist stlist = new Gson().fromJson(temp.toString(), Statelist.class);
slist = new ArrayList<String>();
// clistModels = new ArrayList<Country>();
//clistModels.add(new Country(temp.optString("id"), temp.optString("country_name"), "", null));
slist.add(temp.getString("state_name"));
sad = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, slist);
spstate.setAdapter(sad);
spstate.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// strcnt = clistModels.get(position).getId();
//strcnt = parent.getItemAtPosition(position).toString();
// Log.i("id", strcnt);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// txtid.setText(temp.getString(country.getId()));
// txtcname.setText(temp.getString(country.getCountryName()));
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
My response is null?
HttpURLConnection is deprecated in Android Lollipop, so please try to use DefaultHttpClient instead. Also, check your logs, this is at your onPostExecute():
Log.i("Result Ravi", result);
For DefaultHttpClient check this post.
Another way is to try Retrofit

Android: white screen while onCreate

I have an app that at launch inside onCreate method copies data from assets folder. It does it in three for cycles, each with activity indicator and the problem is that when first two cycles run white screen shows and only when third loop starts i can seen activity screen with indicator on it.
The code is following
Realm realm;
ListView list;
int[] imageidsm = {R.drawable.fon_sovety350, R.drawable.fon_german350, R.drawable.fon_usa350, R.drawable.fon_uk350, R.drawable.fon_fr_it200, R.drawable.fon_japan_china200, R.drawable.fon_history200};
String[] itemname = {"СССР", "ГЕРМАНИЯ", "США", "ВЕЛИКОБРИТАНИЯ", "ФРАНЦИЯ И ИТАЛИЯ", "ЯПОНИЯ И КИТАЙ", "ИСТОРИЯ"};
Boolean firstLaunch = false;
SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = metrics.heightPixels;
int width = metrics.widthPixels;
MainAdapter adapter = new MainAdapter(this, itemname, imageidsm, height, width);
list = (ListView) findViewById(R.id.mainListView);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 2) {
Intent toSssr = new Intent(MainActivity.this, TankListActivity.class);
toSssr.putExtra("category", "СССР");
startActivity(toSssr);
} else if (position == 3) {
Intent listActivity = new Intent(MainActivity.this, ArticleListActivity.class);
startActivity(listActivity);
}
}
});
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this)
.name("db.realm")
.build();
realm.setDefaultConfiguration(realmConfiguration);
realm = Realm.getDefaultInstance();
preferences = getApplicationContext().getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
firstLaunch = preferences.getBoolean("firstLaunch", false);
if (firstLaunch == false) {
firstLaunch();
}
}
public void firstLaunch() {
String[] arrayOfCatLists = {"00f.json", "01f.json", "02f.json", "10f.json"};
String[] arrayOfArticles = {"32.json", "34.json", "44.json", "51.json", "33.json", "40.json", "41.json", "42.json", "52.json", "45.json", "37.json", "46.json", "36.json", "54.json", "35.json", "43.json", "47.json", "50.json", "49.json", "48.json", "56.json", "58.json", "53.json", "59.json" , "55.json", "60.json", "61.json"};
String[] arrayOfUsssr = {"62.json", "74.json", "75.json", "76.json", "63.json", "78.json", "79.json", "77.json", "81.json", "80.json"};
for (int i = 0; i < arrayOfCatLists.length; i++) {
new GetArticlesListFromDisk(arrayOfCatLists[i], i).execute();
}
for (int i = 0; i < arrayOfArticles.length; i++) {
new GetArticleFromDisk(arrayOfArticles[i]).execute();
}
for (int i = 0; i < arrayOfUsssr.length; i++) {
new GetTanksFromDisk(arrayOfUsssr[i]).execute();
}
firstLaunch = true;
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("firstLaunch", firstLaunch);
editor.apply();
}
private class GetArticlesListFromDisk extends AsyncTask<String, Void, String> {
private String id;
private int index;
String[] arrayOfCatLists = {"00f.json", "01f.json", "02f.json"};
private GetArticlesListFromDisk(String id, int index) {
this.id = id;
this.index = index;
}
ProgressDialog pd = new ProgressDialog(MainActivity.this);
#Override
protected String doInBackground(String... params) {
String json = null;
try {
InputStream input = getApplicationContext().getAssets().open(id);
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
json = new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return json;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd.setCancelable(false);
pd.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
pd.setMessage("Минуточку, загружаемся");
pd.show();
}
#Override
protected void onPostExecute(String strJson) {
super.onPostExecute(strJson);
pd.dismiss();
JSONObject dataJsonObj = null;
String category = "";
try {
dataJsonObj = new JSONObject(strJson);
JSONArray listing = dataJsonObj.getJSONArray("listing");
for (int i = 0; i < listing.length(); i++) {
JSONObject object = listing.getJSONObject(i);
String id = object.getString("id");
String title = object.getString("title");
String subtitle = object.getString("subtitle");
String image = object.getString("image");
InputStream inputStream =null;
Bitmap bitmap = null;
try {
inputStream = getAssets().open(image);
bitmap = BitmapFactory.decodeStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
Log.d("getArticleFromDisk", "Saved article " + title);
ImageStorage.saveToSdCard(bitmap, image, getApplicationContext());
if (index == 0) {
category = "Танковые сражения";
} else if (index == 1) {
category = "Справочник танкиста";
} else if (index == 2) {
category = "Танковые асы";
} else if (index == 3) {
category = "СССР";
} else if (index == 4) {
category = "Германия";
} else if (index == 5) {
category = "США";
} else if (index == 6) {
category = "Великобритания";
}
realm.beginTransaction();
ArticleList articleList = realm.createObject(ArticleList.class);
articleList.setId(id);
articleList.setTitle(title);
articleList.setSubtitle(subtitle);
articleList.setImage(image);
articleList.setCategory(category);
realm.commitTransaction();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private class GetArticleFromDisk extends AsyncTask<String, Void, String> {
private String id;
private int categoryIndex;
private GetArticleFromDisk(String id) {
this.id = id;
}
public String LOG_TAG = "GetArticleFromDisk";
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String resultJson = "";
ProgressDialog pd = new ProgressDialog(MainActivity.this);
#Override
protected String doInBackground(String... params) {
String json = null;
try {
InputStream input = getApplicationContext().getAssets().open(id);
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
json = new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return json;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd.setCancelable(false);
pd.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
pd.setMessage("Минуточку, загружаемся");
pd.show();
}
#Override
protected void onPostExecute(String strJson) {
super.onPostExecute(strJson);
pd.dismiss();
JSONObject dataJsonObj = null;
String category = "";
try {
dataJsonObj = new JSONObject(strJson);
JSONArray listing = dataJsonObj.getJSONArray("article");
for (int i = 0; i < listing.length(); i++) {
JSONObject object = listing.getJSONObject(i);
String id = object.getString("id");
String title = object.getString("title");
String subtitle = object.getString("subtitle");
String body = object.getString("body");
String hash = object.getString("content_version");
Log.d(LOG_TAG, "Saved article with id " + id);
realm.beginTransaction();
Article article = realm.createObject(Article.class);
article.setId(id);
article.setTitle(title);
article.setSubtitle(subtitle);
article.setBody(body);
article.setHash(hash);
realm.commitTransaction();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private class GetTanksFromDisk extends AsyncTask<String, Void, Tank> {
private String id;
private int categoryIndex;
private GetTanksFromDisk(String id) {
this.id = id;
}
public String LOG_TAG = "GetTankFromDisk";
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String resultJson = "";
ProgressDialog pd = new ProgressDialog(MainActivity.this);
Tank tank = new Tank();
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.d(LOG_TAG, "Entered preExecute");
pd.setCancelable(false);
pd.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
pd.setMessage("Минуточку, загружаемся");
pd.show();
}
#Override
protected Tank doInBackground(String... params) {
String json = null;
try {
InputStream input = getApplicationContext().getAssets().open(id);
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
json = new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
JSONObject dataJsonObj = null;
String category = "";
try {
dataJsonObj = new JSONObject(json);
JSONArray listing = dataJsonObj.getJSONArray("article");
for (int i = 0; i < listing.length(); i++) {
JSONObject object = listing.getJSONObject(i);
String id = object.getString("id");
String title = object.getString("title");
JSONArray signatures = object.getJSONArray("signatures");
ArrayList<String> signatures_list = new ArrayList<String>();
for (int j = 0; j < signatures.length(); j++) {
signatures_list.add(signatures.get(j).toString());
}
String signatures_string = Joiner.on(",").join(signatures_list);
String body = object.getString("body");
String construction = object.getString("construction");
String modification = object.getString("modification");
String ttx = object.getString("ttx");
JSONObject images = object.getJSONObject("images");
JSONArray tank_slider = images.getJSONArray("tank_slider");
ArrayList<String> tank_slider_list = new ArrayList<String>();
for (int k = 0; k < tank_slider.length(); k++) {
InputStream inputStream =null;
Bitmap bitmap = null;
try {
inputStream = getAssets().open(tank_slider.getString(k));
bitmap = BitmapFactory.decodeStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
ImageStorage.saveToSdCard(bitmap, tank_slider.getString(k), getApplicationContext());
tank_slider_list.add(tank_slider.getString(k));
}
String tank_slider_string = Joiner.on(",").join(tank_slider_list);
String hash = object.getString("content_version");
Log.d(LOG_TAG, "Imported from assets tank with id " + id);
tank.setId(id);
tank.setTitle(title);
tank.setSignatures(signatures_string);
tank.setBody(body);
tank.setConstruction(construction);
tank.setModification(modification);
tank.setTtx(ttx);
tank.setTank_slider(tank_slider_string);
tank.setHash(hash);
}
} catch (JSONException e) {
e.printStackTrace();
}
return tank;
}
#Override
protected void onPostExecute(Tank tank) {
super.onPostExecute(tank);
pd.dismiss();
realm.beginTransaction();
Tank newTank = realm.createObject(Tank.class);
newTank.setId(tank.getId());
newTank.setTitle(tank.getTitle());
newTank.setSignatures(tank.getSignatures());
newTank.setBody(tank.getBody());
newTank.setConstruction(tank.getConstruction());
newTank.setModification(tank.getModification());
newTank.setTtx(tank.getTtx());
newTank.setTank_slider(tank.getTank_slider());
newTank.setHash(tank.getHash());
realm.commitTransaction();
}
}
What Im I doing wrong ?

GridView not refreshing after changing setting

I am building this movie app that displays movies in a gridview on the main panel, then I can click them and display some information about that movie, also I have some settings to change the criteria of the movies displayed: popular, top rated or favorites. The favorites are a local collection saved in sharedPreferences chosen by the user.
Here is where it all happens:
public class MovieFragment extends Fragment{
public String[][] matrixMoviesInfo;
public GridView gridView;
public String[] mArrayImages;
private String baseUrl;
private String apiKey;
public MovieFragment(){
matrixMoviesInfo = new String[20][10];
mArrayImages = new String[20];
baseUrl = "http://api.themoviedb.org/3/movie/";
apiKey = "?api_key=37068e0a72b2cc1751b4246899923ba7";
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
gridView = (GridView) rootView.findViewById(R.id.gridview);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Intent intent = new Intent(getActivity(), DetailActivity.class)
.putExtra(Intent.EXTRA_TEXT, matrixMoviesInfo[position]);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
});
return rootView;
}
private void setImages() {
for(int i=0;i<mArrayImages.length;i++){
if(matrixMoviesInfo[i][0]!=null) {
mArrayImages[i] = matrixMoviesInfo[i][0];
}
}
gridView.setAdapter(null);
gridView.setAdapter(new ImageAdapter(getActivity(), mArrayImages));
Log.v(null, "SETIMAGESCALLED");
}
private void updateMovies() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String preference = prefs.getString(getString(R.string.pref_sortby_key), getString(R.string.pref_sortby_default));
if(preference.toLowerCase().equals("favorites")){
SharedPreferences preferences = getContext().getSharedPreferences("favorites_list", Context.MODE_PRIVATE);
Map<String, ?> allEntries = preferences.getAll();
String[] keyNames = new String[allEntries.size()];
Log.v(null,"SIZE: "+allEntries.size());
String[] keyValues;
int iterator=0;
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
Log.v("KEY: " +entry.getKey(), "VALUE: "+entry.getValue().toString());
}
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
if(entry.getKey()!=null) {
keyNames[iterator] = entry.getKey();
keyValues = entry.getValue().toString().split("#");
for (int i = 0; i < 10; i++) {
Log.v("INDEX: " + i, " VALUES: " + keyValues[i]);
matrixMoviesInfo[iterator][i] = keyValues[i];
}
iterator++;
}
}
setImages();
}else{
Log.v(null,"EXECUTETASK");
new FetchMoviesTask().execute(baseUrl+preference.toLowerCase()+apiKey, "i");
}
}
#Override
public void onStart() {
super.onStart();
updateMovies();
}
public class FetchMoviesTask extends AsyncTask<String, String, Void> {
private final String LOG_TAG = FetchMoviesTask.class.getSimpleName();
private Void getMovieDetailsFromJson(String movieJSONstr) throws JSONException {
final String OWM_RESULTS = "results";
final String OWM_ID = "id";
final String OWM_POSTERPATH = "poster_path";
final String OWM_TITLE = "original_title";
final String OWM_OVERVIEW = "overview";
final String OWM_USERRATING = "vote_average";
final String OWM_RELEASEDATE = "release_date";
JSONObject movieJson = new JSONObject(movieJSONstr);
JSONArray movieArray = movieJson.getJSONArray(OWM_RESULTS);
for(int i = 0; i < movieArray.length(); i++) {
JSONObject movieObj = movieArray.getJSONObject(i);
matrixMoviesInfo[i][0] = movieObj.getString(OWM_POSTERPATH);
matrixMoviesInfo[i][1] = movieObj.getString(OWM_ID);
matrixMoviesInfo[i][2] = movieObj.getString(OWM_TITLE);
matrixMoviesInfo[i][3] = movieObj.getString(OWM_OVERVIEW);
matrixMoviesInfo[i][4] = movieObj.getString(OWM_USERRATING);
matrixMoviesInfo[i][5] = movieObj.getString(OWM_RELEASEDATE);
}
for(int i=0;i<20;i++) {
new FetchMoviesTask().execute(baseUrl + matrixMoviesInfo[i][1] + "/reviews" + apiKey, Integer.toString(i));
new FetchMoviesTask().execute(baseUrl + matrixMoviesInfo[i][1] + "/videos" + apiKey, "v");
}
Log.v(null,"GETMOVIEDETAILS");
return null;
}
private Void getMovieReviewsFromJson(String movieJSONstr, String position) throws JSONException{
int pos = Integer.parseInt(position);
final String OWM_RESULTS = "results";
final String OWM_AUTHOR = "author";
final String OWM_CONTENT = "content";
final String OWM_TOTALRESULTS = "total_results";
JSONObject movieJson = new JSONObject(movieJSONstr);
JSONArray movieArray = movieJson.getJSONArray(OWM_RESULTS);
int numberOfResults = Integer.parseInt(movieJson.getString(OWM_TOTALRESULTS));
if(numberOfResults >= 1) {
matrixMoviesInfo[pos][6] = movieArray.getJSONObject(0).getString(OWM_AUTHOR);
matrixMoviesInfo[pos][7] = movieArray.getJSONObject(0).getString(OWM_CONTENT);
}
if(numberOfResults > 1) {
matrixMoviesInfo[pos][8] = movieArray.getJSONObject(1).getString(OWM_AUTHOR);
matrixMoviesInfo[pos][9] = movieArray.getJSONObject(1).getString(OWM_CONTENT);
}
return null;
}
private Void getMovieVideosFromJson(String movieJSONstr){
return null;
}
#Override
protected Void doInBackground(String... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String movieJSONstr = null;
try{
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if(inputStream == null){
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while((line = reader.readLine()) != null){
buffer.append(line + "\n");
}
if(buffer.length() == 0){
movieJSONstr = null;
}
movieJSONstr = buffer.toString();
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
return null;
} finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("MovieFragment", "Error closing stream", e);
}
}
}
try{
if(params[1].equals("i")){
Log.v(null,"EXECUTEGETMOVIEDETAILS");
return getMovieDetailsFromJson(movieJSONstr);
}
else {
if (params[1].equals("v")){
return getMovieVideosFromJson(movieJSONstr);}
else{
return getMovieReviewsFromJson(movieJSONstr, params[1]);}
}
}catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
String[] mArrayImages = new String[20];
for(int i=0;i<20;i++){
mArrayImages[i] = matrixMoviesInfo[i][0];
}
gridView.setAdapter(new ImageAdapter(getActivity(), mArrayImages));
Log.v(null, "IMAGES SET GRIDVIEW REFRESHED");
}
}
Class Explanation:
There is 2 paths:
Popular or TopRated: starts on method UpdateMovies, then executes the asynctask to fetch data from the api, followed by the execution of the getMoviesFromJson that extracts all the information related to all movies. Then it ends on onPostExecute that populates the gridview with the ImageAdapter.
Favorites: starts on method UpdateMovies, here it fetchs the data from sharedpreferences and populates the array with that data, then it calls the method setImages to populate the gridView with the ImageAdapter.
Here is my problem: when I am displaying the popular movies and change the setting to favorites, it displays the right movies on the sharedpreferences but it is not "cleaning" the remaining ones from the gridview.
Also how can I adjust the scroll of the gridview to match the cells it has (when there is no movie to populate a cell, I hide it like this:
imageView.setVisibility(View.GONE);
Make an Adapter for the gridview that extends from BaseAdapter, or use an Adapter that extends from BaseAdapter.
then call notifyDataSetChanged on that adapter when the contents of your collection has changed.

android-amazing-listview, how Can I update the new page load by passing data to the URL

On the auto load, I need to be able to load more items from the URL. Where I am getting my Data via Json.
in my API call class I need to add to this nuber 10 as:
pairs.add(new BasicNameValuePair("limit", "10"));
Whenever the list view finish loading the currently data, then changes the value above and check again.
I though I needed to create a method in PaginationDemoActivity where it check for if more pages, then use intent to pass a new variable to overwrite ("limit", "10")) in the JSONfunctions class
Any advice ? Thanks guys
JSONfunctions
public class JSONfunctions extends Activity{
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
//Add URL Encoding by sending post data
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("c","getlist"));
pairs.add(new BasicNameValuePair("page","1"));
pairs.add(new BasicNameValuePair("limit", "10"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,HTTP.UTF_8);
httppost.setEntity(entity);
// end Add URL Encoding by sending post data
HttpResponse httpResponse = httpclient.execute(httppost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
//end test
/*
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
*/
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
Data
public class Data {
static String URL = " my api url";
static String itemsPerPage = "20";
public static final String TAG = Data.class.getSimpleName();
public static List<Pair<String, List<Composer>>> getAllData() {
List<Pair<String, List<Composer>>> res = new ArrayList<Pair<String, List<Composer>>>();
for (int i = 0; i < 4; i++) {
res.add(getOneSection(i));
}
return res;
}
public static List<Composer> getFlattenedData() {
List<HashMap<String, String>> arraylist;
JSONObject jsonobject;
JSONArray jsonarray;
List<Composer> res = new ArrayList<Composer>();
//Pair<String, List<Composer>> mydata;
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL(URL);
Log.e("check", jsonobject.toString());
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("id", jsonobject.getString("id"));
map.put("title", jsonobject.getString("title"));
map.put("s_desc", jsonobject.getString("s_desc"));
map.put("img", jsonobject.getString("img"));
// Set the JSON Objects into the array
arraylist.add(map);
Composer s = new Composer(
jsonobject.getString("title"),
jsonobject.getString("s_desc"),
jsonobject.getString("id"),
jsonobject.getString("img"));
res.add(s);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return res;
}
protected void updateUrlItems()
{
}
public static Pair<Boolean, List<Composer>> getRows(int page) {
List<Composer> flattenedData = getFlattenedData();
if (page == 1) {
return new Pair<Boolean, List<Composer>>(true, flattenedData.subList(0, 5));
} else {
SystemClock.sleep(2000); // simulate loading
return new Pair<Boolean, List<Composer>>(page * 5 < flattenedData.size(),
flattenedData.subList((page - 1) * 5, Math.min(page * 5, flattenedData.size())));
}
}
public static Pair<String, List<Composer>> getOneSection(int index) {
String[] titles = {"", "", "", ""};
Composer[][] composerss = {
{
new Composer("", "", "", ""),
},
};
return new Pair<String, List<Composer>>(titles[index], Arrays.asList(composerss[index]));
}
}
PaginationDemoActivity
public class PaginationDemoActivity extends Activity {
AmazingListView lsComposer;
PaginationComposerAdapter adapter;
ImageLoader imageLoader;
// Flag for current page
static Integer current_page = 10;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pagination_demo);
imageLoader = new ImageLoader(this);
lsComposer = (AmazingListView) findViewById(R.id.lsComposer);
lsComposer.setLoadingView(getLayoutInflater().inflate(R.layout.loading_view, null));
lsComposer.setAdapter(adapter = new PaginationComposerAdapter());
adapter.notifyMayHaveMorePages();
}
public void bRefresh_click(View v) {
adapter.reset();
adapter.resetPage();
adapter.notifyMayHaveMorePages();
}
class PaginationComposerAdapter extends AmazingAdapter {
List<Composer> list = Data.getRows(1).second;
private AsyncTask<Integer, Void, Pair<Boolean, List<Composer>>> backgroundTask;
public void reset() {
if (backgroundTask != null) backgroundTask.cancel(false);
list = Data.getRows(1).second;
notifyDataSetChanged();
}
#Override
public int getCount() {
return list.size();
}
#Override
public Composer getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
protected void onNextPageRequested(int page) {
Log.d(TAG, "Got onNextPageRequested page=" + page);
if (backgroundTask != null) {
backgroundTask.cancel(false);
}
backgroundTask = new AsyncTask<Integer, Void, Pair<Boolean, List<Composer>>>() {
#Override
protected Pair<Boolean, List<Composer>> doInBackground(Integer... params) {
int page = params[0];
Log.e("more page", "page: " + page);
return Data.getRows(page);
}
#Override
protected void onPostExecute(Pair<Boolean, List<Composer>> result) {
if (isCancelled()) return;
Log.e("onPostExecute", "result: " + result.first);
list.addAll(result.second);
nextPage();
notifyDataSetChanged();
if (result.first) {
// still have more pages
notifyMayHaveMorePages();
} else {
notifyNoMorePages();
}
};
}.execute(page);
}
#Override
protected void bindSectionHeader(View view, int position, boolean displaySectionHeader) {
}
#Override
public View getAmazingView(int position, View convertView, ViewGroup parent) {
View res = convertView;
if (res == null) res = getLayoutInflater().inflate(R.layout.item_composer, null);
// we don't have headers, so hide it
res.findViewById(R.id.header).setVisibility(View.GONE);
TextView lName = (TextView) res.findViewById(R.id.lName);
TextView lYear = (TextView) res.findViewById(R.id.lYear);
TextView lId = (TextView) res.findViewById(R.id.lId);
// Locate the ImageView in listview_item.xml
ImageView lImg = (ImageView) res.findViewById(R.id.lImg);
Composer composer = getItem(position);
lName.setText(composer.name);
lYear.setText(composer.year);
lId.setText(composer.id);
Log.e("getAmazingView PRINT THE URL 1111111111", "URL: " + composer.img);
// Capture position and set results to the ImageView
// Passes img images URL into ImageLoader.class
imageLoader.DisplayImage(composer.img, lImg);
Log.e("222","333");
//khen
lsComposer.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// TODO Auto-generated method stub
if(id > -1){
Composer composer = adapter.getItem(position);
Intent intent = new Intent();
intent.setClass(getApplicationContext(), SingleItemView.class);
Bundle bundle = new Bundle();
bundle.putString("id", composer.id);
bundle.putString("name", composer.name);
bundle.putString("year", composer.year);
bundle.putString("img", composer.img);
intent.putExtras(bundle);
startActivity(intent);
}
}
});
//end khen
return res;
}
#Override
public void configurePinnedHeader(View header, int position, int alpha) {
}
#Override
public int getPositionForSection(int section) {
return 0;
}
#Override
public int getSectionForPosition(int position) {
return 0;
}
#Override
public Object[] getSections() {
return null;
}
}
}

Categories

Resources