Blank image is shown and onItemClick wont work - java

I am working on an Android project in which I have to display some images in a list. For this, I am using an Adapter. I don't see any errors when I run the code, but no image is displayed. Also, I have set an onClickListener, and a Log.d inside it. But the Log.d is not displayed. What am I doing wrong?
public class OtherUsers extends Activity {
private PersonServiceImpl personService = new PersonServiceImpl();
private static volatile List<RestPerson> restPersonList = new ArrayList<>();
public static final String firstName = "firstname";
public static final String userImage = "userimage";
static final String userId = "0";
ListView listView;
UserAdapter userAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.displayuserlist);
restPersonList = this.personService.getOtherUsers();
ArrayList<HashMap<String, String>> usersArrayHashList = new ArrayList<>();
for (RestPerson restPerson : restPersonList) {
HashMap<String, String> restDisplay = new HashMap<>();
restDisplay.put(userId, String.valueOf(restPerson.getUserId()));
restDisplay.put(firstName, restPerson.getFirstName());
restDisplay.put(userImage, restPerson.getProfilePhoto());
usersArrayHashList.add(restDisplay);
}
listView = (ListView) findViewById(R.id.usersdisplaylist);
userAdapter = new UserAdapter(this, usersArrayHashList);
listView.setAdapter(userAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.d("Item", "wasclicked");
Long userid = restPersonList.get(position).getUserId();
Log.d("Userid is ", String.valueOf(userid));
}
});
}
}
Adapter class :
public class UserAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public UserAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.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 view = convertView;
if (convertView == null)
view = inflater.inflate(R.layout.userprofiles, null);
TextView username = (TextView) view.findViewById(R.id.userName);
ImageView userImage = (ImageView) view.findViewById(R.id.userImage);
HashMap<String, String> usersList = new HashMap<>();
usersList = data.get(position);
username.setText(usersList.get(OtherUsers.firstName));
byte [] encodeByte=Base64.decode(usersList.get(OtherUsers.userImage).getBytes(), Base64.DEFAULT);
Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
userImage.setImageBitmap(bitmap);
return view;
}
}
No image is seen, cant see in Log.d the clicked id. Unfortunately no errors to diagnose whats wrong.
Update
userprofiles.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dip" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="15dp"
android:orientation="vertical"
android:weightSum="1">
<ImageView
android:id="#+id/userImage"
android:layout_width="140dp"
android:layout_height="200dp"
android:scaleType="fitXY"
android:padding="5dp"
android:src="#drawable/profile"
/>
<TextView
android:id="#+id/userName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="visible"
android:gravity="center"
android:layout_gravity="center_horizontal|top"
android:maxLines="1"
android:ellipsize="end"
android:scrollHorizontally="true"
android:layout_marginTop="10dp"
android:layout_weight="1.10" />
</LinearLayout>
</RelativeLayout>
PhotoSaving code :
public class AddPhotoForUser extends Activity {
private static final int CAMERA_PIC_REQUEST = 22;
Button BtnSelectImage;
private ImageView ImgPhoto;
private static volatile Bitmap photo;
private static volatile ByteArrayOutputStream stream = new ByteArrayOutputStream();
final PersonServiceImpl personService = new PersonServiceImpl();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.upload_user_photo);
Button uploadImageButton = (Button) findViewById(R.id.uploadUserImageButton);
uploadImageButton.setVisibility(View.INVISIBLE);
ImgPhoto = (ImageView) findViewById(R.id.userPhotoImageView);
BtnSelectImage = (Button) findViewById(R.id.userPhotoButtonSelect);
BtnSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Couldn't load photo", Toast.LENGTH_LONG).show();
}
}
});
uploadImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!(v == null)) {
uploadImage();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Intent intent = new Intent(AddPhotoForUser.this, RestaurantList.class);
startActivity(intent);
finish();
}
}
});
}
#Override
public void onBackPressed() {
Intent intent = new Intent(AddPhotoForUser.this, Login.class);
startActivity(intent);
finish();
}
#Override
public void onActivityResult(final int requestCode, int resultCode, Intent data) {
try {
switch (requestCode) {
case CAMERA_PIC_REQUEST:
if (resultCode == RESULT_OK) {
try {
photo = (Bitmap) data.getExtras().get("data");
if (!(photo == null)) {
ImgPhoto.setImageBitmap(photo);
Button uploadImageButton = (Button) findViewById(R.id.uploadUserImageButton);
uploadImageButton.setVisibility(View.VISIBLE);
}
} catch (Exception e) {
Toast.makeText(this, "Couldn't load photo", Toast.LENGTH_LONG).show();
}
}
break;
default:
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void uploadImage() {
if (!(photo == null)) {
photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
personService.addUserProfilePhoto(Base64.encodeToString(byteArray, Base64.DEFAULT));
}
}
}
Now , this calls the method to save it in DB. Currently, because byte-array was harassing so much, I have changed it to String.
Here is how it looks in DB now :
ImlWQk9SdzBLR2dvQUFBQU5TVWhFVWdBQUFLQUFBQUI0Q0FJQUFBRDZ3RzQ0QUFBQUEzTkNTVlFJ
Q0FqYjRVL2dBQUFDZlVsRVFWUjRcbm5PM2RNWkxTWUJpQTRlOTNNcE40QmtvT29CVjBNTE9sVmg1
Q08rZ292SUUxV0ducEFUekMxcFI2QnpydHRXSUx0akpqTmo4a0pMejdcblB1V1NmUG1YZDhqT0xB
bWt6V1lURWJ2ZExuS3NWcXVzN1owLzFQd1hXWE4xY3d3TVoyQzRvbytoNzc1KytmY25WWmszb2pi
aGlTTldcblpVVGMvZm1iZDVSbndGY3dYSnBPcHhFeG44K3pkdHZ2OXcyUGZ2djk2NkpGbmV2em03
Y3R0MnhlZjEyM3o4ODE1eGVId3lFaUpwTkpcbjFnRk9lLzFYN2dtNUkrMS9peWZXZjhIa3NjMzNG
QTFuWURnRHd4a1l6c0J3Qm9Zek1KeUI0UXdNWjJBNEE4TVpHTTdBY0FhR1M0dkZcbklpSlNTbG03
SFkvSGhrYy8vZnh4MGFMTzlmSFY2NVpiTnErL3J0dm41NXJ6aTlOYnpSMWZ0amxRNFBadmc0L25z
dGErNTN1S2hqTXdcbm5JSGhEQXhuWURnRHd4a1l6c0J3Qm9Zek1KeUI0UXdNWjJBNEE4UDFjL3Zv
UUx4OXRDNlZaUmtSNi9VNjZ3RGI3YmJoMGZ1WFZkYTBcbnJueC8vNkhsbHMzcnIrdjIrYm5tL0NM
M1dvS1Q4L1lhajc3WFA1NzUvZzJHTXpDY2dlRjYrWnlzK3VkVmplY2l0T2ZHVnpDY2dlRU1cbkRH
ZGdPQVBER1JqT3dIQUdoak13bklIaGl0TS8rVzczL2xmbk4vTVZER2RnT0FQREdSak93SEFHaGpN
d25JSGhEQXhuWURnRHd4a1lcbnpzQndCb1o3dkxNaDkvT05jemwvcVBtOWZFRjBuZk9IbW4rbE8v
eWRQOVI4L3diREdSak93SEFHaGpNd25JSGhEQXhuWURnRHd4a1lcbnpzQndCb1l6TUp5QjRkSnl1
WXd4ZmFHeDg3dWRYOHhtczdqbEc1eWQzOHhUTkp5QjRRd01aMkE0QThNWkdNN0FjQWFHTXpDY2dl
RU1cbkRHZGdPQVBER1JqTzIwZmg4MU5WVlRHbTl5K2QzKzE4VDlGd0JvWXpNSnlCNFF3TVoyQTRB
OE1aR003QWNBYUdNekNjZ2VFTURHZGdcbk9BUERQUUE2L2ZhYjNyY3BjQUFBQUFCSlJVNUVya0pn
Z2c9PVxuIg==
Below methods are used to add photo and retrieve users from server :
#Override
public void addUserProfilePhoto(final String profilePhoto) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
HttpHeaders headers = new HttpHeaders();
headers.add("Cookie", "JSESSIONID=" + StaticRestTemplate.jsessionid);
// headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(profilePhoto, headers);
ResponseEntity<Boolean> out = restTemplate.exchange(addPhotoUrl, HttpMethod.POST, entity, Boolean.class);
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
#Override
public List<RestPerson> getOtherUsers() {
final RestTemplate restTemplate = StaticRestTemplate.getRest();
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.add("Cookie", "JSESSIONID=" + StaticRestTemplate.jsessionid);
requestHeaders.setAccept(Collections.singletonList(new MediaType("application", "json")));
HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
responseEntity = restTemplate.exchange(getOtherusers, HttpMethod.GET, requestEntity, RestPerson[].class);
}
});
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
RestPerson[] restPersonsArray = responseEntity.getBody();
List<RestPerson> restPersonArrayList = new ArrayList<>();
Collections.addAll(restPersonArrayList, restPersonsArray);
return restPersonArrayList;
}

Ensure you have set
android:descendantFocusability="blocksDescendants" in your R.layout.userprofiles.
This prevent that other focusable or clickable item in your row definition intercept row click.
Secondly, try to set a background color to your imageview and very that this "colored" view is really visible or not.
Edit
Finaly your getItem on adapter class is wrong: you have to return data.get(position)

First thing, You set the image bitmap twice here:
userImage.setImageBitmap(bitmap);
userImage.setImageBitmap(null);
make sure to remove the last line, which sets the image bitmap to null.
About the onItemClickListener, make sure you cleared the logcat filtering text, selected Log level to debug, and select the option "No filters" instead of "Show only selected Application" just to be sure you are not filtering out Your logs.

Check if the count of restPersonList is equal to 0,and add a log in method getView。

Related

App crashes after theme change (apparently caused by fragment)

My Main Activity has three tabs. Each tab is a fragment. Now if you change the theme (white and dark are available), the activity is being recreated so that the change takes effect. But the app crashes.
How I deal with the fragments:
if (savedInstanceState == null) {
pageadapter = new SectionsPageAdapter(getSupportFragmentManager());
rFragMore = new RoomlistFragmentMore();
rFragMyRooms = new RoomlistFragmentMyRooms();
rFragFavs = new RoomlistFragmentFavorites();
} else {
rFragMyRooms = (RoomlistFragmentMyRooms)pageadapter.getItem(0);
rFragFavs = (RoomlistFragmentFavorites)pageadapter.getItem(1);
rFragMore = (RoomlistFragmentMore)pageadapter.getItem(2);
pageadapter.clearAdapter();
pageadapter = new SectionsPageAdapter(getSupportFragmentManager());
}
How I set up the Adapter:
private void setupViewPager(ViewPager viewPager) {
pageadapter.addFragment(rFragMyRooms, getResources().getString(R.string.myrooms));
pageadapter.addFragment(rFragFavs, getResources().getString(R.string.favorites));
pageadapter.addFragment(rFragMore, getResources().getString(R.string.more));
viewPager.setAdapter(pageadapter);
}
My Adapter:
public class SectionsPageAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
public void clearAdapter() {
mFragmentList.clear();
mFragmentTitleList.clear();
}
public SectionsPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
}
And the Error Log:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.FileInputStream android.content.Context.openFileInput(java.lang.String)' on a null object reference
at com.yannick.mychatapp.RoomlistFragmentMore.readFromFile(RoomlistFragmentMore.java:246)
at com.yannick.mychatapp.RoomlistFragmentMore.addRoomToList(RoomlistFragmentMore.java:121)
at com.yannick.mychatapp.RoomlistFragmentMore.access$000(RoomlistFragmentMore.java:46)
at com.yannick.mychatapp.RoomlistFragmentMore$1.onDataChange(RoomlistFragmentMore.java:79)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database##16.0.4:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database##16.0.4:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database##16.0.4:55)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
EDIT: the code of RoomlistFragmentMore
public class RoomlistFragmentMore extends Fragment {
private ListView listView;
private List<HashMap<String, String>> listItems = new ArrayList<>();
private String raumname, theme;
private static String userID = "";
private SimpleAdapter adapter;
private DatabaseReference root = FirebaseDatabase.getInstance().getReference().getRoot().child("rooms");
private ArrayList<Room> raumliste = new ArrayList<>();
private TextView keinraumgefunden;
private String[] kat;
private static final String TAG = "RoomlistFragmentMore";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.roomlist_fragment_more,container,false);
listView = view.findViewById(R.id.listView);
keinraumgefunden = view.findViewById(R.id.keinraumgefunden);
kat = getResources().getStringArray(R.array.categories);
theme = readFromFile("mychatapp_theme.txt");
adapter = new SimpleAdapter(getActivity(), listItems, R.layout.listlayout,
new String[]{"name", "kat", "lock", "newest"},
new int[]{R.id.raumname, R.id.raumkat, R.id.raumlock, R.id.raumdatum});
listView.setAdapter(adapter);
root.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
addRoomToList(dataSnapshot);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getActivity(), R.string.nodatabaseconnection, Toast.LENGTH_SHORT).show();
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
int position = listView.getPositionForView(view);
String roomname = listItems.get(position).values().toArray()[0].toString();
Room room = findRoom(raumliste, roomname);
request_password(room, position);
}
});
adapter.registerDataSetObserver(new DataSetObserver() {
#Override
public void onChanged() {
if (raumliste.isEmpty()) {
keinraumgefunden.setText(R.string.noroomfound);
} else {
keinraumgefunden.setText("");
}
}
});
return view;
}
private void addRoomToList(DataSnapshot dataSnapshot) {
HashMap<String, String> raeume = new HashMap<>();
raumliste.clear();
for(DataSnapshot uniqueKeySnapshot : dataSnapshot.getChildren()){
String name = uniqueKeySnapshot.getKey();
for(DataSnapshot roomSnapshot : uniqueKeySnapshot.getChildren()){
Room room = roomSnapshot.getValue(Room.class);
room.setRaumname(name);
if (!room.getPasswd().equals(readFromFile("mychatapp_raum_" + name + ".txt"))) {
raeume.put(name, kat[Integer.parseInt(room.getCaty())]+"/"+"\uD83D\uDD12"+"/");
raumliste.add(room);
}
break;
}
}
listItems.clear();
Iterator it = raeume.entrySet().iterator();
while (it.hasNext()){
HashMap<String, String> resultsMap = new HashMap<>();
Map.Entry pair = (Map.Entry)it.next();
resultsMap.put("name", pair.getKey().toString());
String daten = pair.getValue().toString();
String caty = daten.substring(0, daten.indexOf("/"));
String lock = daten.substring(daten.indexOf("/")+1, daten.lastIndexOf("/"));
String time = daten.substring(daten.lastIndexOf("/")+1, daten.length());
String newestTime = "";
int index = 0;
resultsMap.put("kat", caty);
resultsMap.put("lock", lock);
resultsMap.put("newest", newestTime);
if (time.equals("")) {
listItems.add(resultsMap);
} else {
listItems.add(index, resultsMap);
}
}
adapter.notifyDataSetChanged();
}
private void request_password(final Room room, final int position) {
LayoutInflater inflater = LayoutInflater.from(getContext());
View view = inflater.inflate(R.layout.enter_room, null);
raumname = room.getRaumname();
userID = readFromFile("mychatapp_userid.txt");
final EditText input_field = view.findViewById(R.id.room_password);
AlertDialog.Builder builder;
if (theme.equals(getResources().getStringArray(R.array.themes)[1])) {
builder = new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), R.style.AlertDialogDark));
} else {
builder = new AlertDialog.Builder(getActivity());
}
builder.setTitle(R.string.pleaseenterpassword);
builder.setView(view);
builder.setCancelable(false);
builder.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
View view = ((AlertDialog) dialogInterface).getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
dialogInterface.cancel();
}
});
final AlertDialog alert = builder.create();
alert.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
Button b = alert.getButton(AlertDialog.BUTTON_POSITIVE);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (input_field.getText().toString().trim().equals(room.getPasswd())) {
Intent tabIntent = new Intent("tab");
LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(tabIntent);
Intent intent = new Intent(getActivity(), ChatActivity.class);
intent.putExtra("room_name", room.getRaumname());
intent.putExtra("user_id",userID);
updateRoomList(position);
writeToFile(room.getPasswd(),"mychatapp_raum_" + raumname + ".txt");
alert.cancel();
startActivity(intent);
} else {
Toast.makeText(getActivity(), R.string.wrongpassword, Toast.LENGTH_SHORT).show();
}
}
});
}
});
alert.show();
}
public Room findRoom(ArrayList<Room> raumliste, String raumname) {
for (Room room : raumliste) {
if (room.getRaumname().equals(raumname)) {
return room;
}
}
return null;
}
public void writeToFile(String text, String datei) {
Context context = getActivity();
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput(datei, Context.MODE_PRIVATE));
outputStreamWriter.write(text);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
public String readFromFile(String datei) {
Context context = getActivity();
String erg = "";
try {
InputStream inputStream = context.openFileInput(datei);
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
erg = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return erg;
}
private void updateRoomList(int position) {
listItems.remove(position);
adapter.notifyDataSetChanged();
}
}
The NullPointerException occured while onDataChange() was executed (you can see this by reading the stack trace). More specifically, readFromFile() needs a valid Context to open a file.
Since your app crashed we know that getActivity() did return null. How can this happen?
You add the ValueEventListener in onCreateView(). At this point in time, the Fragment has a valid Context (see the documentation for an explanation of the Lifecycle), so all is well for the moment.
But since you do not remove the ValueEventListener, it will continue to fire even if the Fragment is temporarily not attached to the Activity because the user swiped to the next page. The Fragment won't be garbage collected because you keep it in a list and reuse it.
This approach is basically ok if you implement null checks to avoid accessing the Activity, the Context or Views in general while they are not present. Of course, you could consider a stronger separation of the data and the View layer as suggested in this guide to app architecture

Parse API Data into TextView

I have a API link that has a json element named title, and I am trying to store that value into a textview. Here is what I have so far in my main activity code that is supposed to display the contained string:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JSONObject jObject;
try {
jObject = new JSONObject("https://chex-triplebyte.herokuapp.com/api/cats?page=0");
String mResponse = jObject.getString("title");
TextView t = (TextView) findViewById(R.id.title_image);
t.setText(mResponse);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The API link I provided works so you can see the value title that I am trying to obtain.
try this:
TextView t = (TextView) findViewById(R.id.title_image);
try {
url = new URL("https://chex-triplebyte.herokuapp.com/api/cats?page=0");
urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.connect();
InputStream in = urlConnection.getInputStream();
reader = new BufferedReader(new InputStreamReader(in));
//InputStreamReader isw = new InputStreamReader(in);
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String JsonResponse= buffer.toString();
JSONObject jsonobj = new JSONObject(JsonResponse);
JSONArray jarray = jsono.getJSONArray("jsontitle");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
t.setText(object.getString("title"));
}
} catch (JSONException e) {
e.printStackTrace();
}
but you have to make sure you have a correct json format like this:
{jsontitle:[{"title":"Space Keybaord Cat","timestamp":"2017-09-11T04:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/space.jpg","description":"In space, no one can hear you purr."},{"title":"Jiji","timestamp":"2017-09-11T03:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/jiji.png","description":"You'd think they'd never seen a girl and a cat on a broom before"},{"title":"Limecat","timestamp":"2017-09-11T02:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/lime.jpg","description":"Destroyer of Clockspider and his evil followers, Limecat is the one true god."},{"title":"Astronaut Cat","timestamp":"2017-09-11T01:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/astronaut.jpg","description":"Houston, we have a purroblem"},{"title":"Grumpy Cat","timestamp":"2017-09-11T00:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/grumpy.jpg","description":"Queen of the RBF"},{"title":"Soviet cat","timestamp":"2017-09-10T23:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/soviet.jpg","description":"In soviet Russia cat pets you!"},{"title":"Serious Business Cat","timestamp":"2017-09-10T22:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/serious.jpg","description":"SRSLY GUISE"},{"title":"Sophisticated Cat","timestamp":"2017-09-10T21:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/sophisticated.PNG","description":"I should buy a boat"},{"title":"Shironeko","timestamp":"2017-09-10T20:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/shironeko.png","description":"The zen master kitty"},{"title":"Puss in Boots","timestamp":"2017-09-10T19:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/puss.jpg","description":"Don't you dare do the litter box on me!"}]}
You need to make a network call first parse it to JSONArray first and then get the title from the JSON
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView t = (TextView) findViewById(R.id.title_image);
RequestQueue queue = Volley.newRequestQueue(this);
String url ="https://chex-triplebyte.herokuapp.com/api/cats?page=0";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONArray jArray;
try {
jArray = new JSONArray(response);
JSONObject jObject = jArray.getJSONObject(0);
String mResponse = jObject.getString("title");
t.setText(mResponse);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
But this will only show the first title in the response array
If you want to show all titles appended then you can loop over the array
JSONArray jArray;
try {
jArray = new JSONArray(response);
String mResponse = "";
for(int i=0 ;i<jArray.length();i++){
JSONObject jObject = jArray.getJSONObject(i);
mResponse += jObject.getString("title")+" ";
}
t.setText(mResponse);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
For using volley you need to include it in dependencies in build.gradle of app
dependencies {
.
.
compile 'com.android.volley:volley:1.0.0'
.
.
}
Try this...
MainActivity.java
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private String TAG = MainActivity.class.getSimpleName();
private ListView listView;
List<RowItem> rowItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
rowItems = new ArrayList<RowItem>();
listView = (ListView) findViewById(R.id.item_list);
new GetList().execute();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1) + ": " + rowItems.get(position),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
class GetList extends AsyncTask<Void, Void, List<RowItem>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(MainActivity.this, "Json Data is downloading", Toast.LENGTH_LONG).show();
}
#Override
protected List<RowItem> doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "https://chex-triplebyte.herokuapp.com/api/cats?page=0";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray list = new JSONArray(jsonStr);
for (int i = 0; i < list.length(); i++) {
JSONObject c = list.getJSONObject(i);
String title = c.getString("title");
String timestamp = c.getString("timestamp");
String image_url = c.getString("image_url");
String description = c.getString("description");
RowItem item = new RowItem();
item.setTitle(title);
item.setTimestamp(timestamp);
item.setImageUrl(image_url);
item.setDescription(description);
rowItems.add(item);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return rowItems;
}
#Override
protected void onPostExecute(List<RowItem> rowItems) {
super.onPostExecute(rowItems);
if (rowItems != null) {
CustomListViewAdapter adapter = new CustomListViewAdapter(MainActivity.this, R.layout.list_item, rowItems);
listView.setAdapter(adapter);
}
}
}
}
CustomListViewAdapter.java
public class CustomListViewAdapter extends ArrayAdapter<RowItem> {
private Context context;
public CustomListViewAdapter(Context context, int resourceId,
List<RowItem> items) {
super(context, resourceId, items);
this.context = context;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDesc;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
RowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.description);
holder.txtTitle = (TextView) convertView.findViewById(R.id.title);
holder.imageView = (ImageView) convertView.findViewById(R.id.preview);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtDesc.setText(rowItem.getDescription());
holder.txtTitle.setText(rowItem.getTitle());
String url = rowItem.getImageUrl();
DownloadImageTask downloadImageTask = new DownloadImageTask(holder.imageView);
downloadImageTask.execute(url);
return convertView;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
RowItem.java
public class RowItem {
private String title;
private String timestamp;
private String imageUrl;
private String description;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/linearLayout2">
<ImageView
android:id="#+id/preview"
android:layout_width="80dp"
android:layout_height="80dp"
app:srcCompat="#mipmap/ic_launcher"
android:contentDescription="#string/app_name" />
<TextView
android:id="#+id/title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:text="#string/app_name"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/preview"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/description"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="#string/app_name"
app:layout_constraintBottom_toBottomOf="#+id/preview"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/preview"
app:layout_constraintTop_toBottomOf="#+id/title" />
</android.support.constraint.ConstraintLayout>
HttpHandler.java
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
activity_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/item_list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Note:
item_list.xml has ConstraintLayout implementation.
Result:

java.lang.IllegalStateException:The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged

I have a sliding image that extends pageradapter. At first it was working. But when i open new activity then press the back button the app is crashing and i've got this error :
java.lang.IllegalStateException: The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged! Expected adapter item count: 10, found: 0 Pager id: malate.denise.chelsie.igphthesisbfinal:id/pager Pager class: class android.support.v4.view.ViewPager Problematic adapter: class malate.denise.chelsie.igphthesisbfinal.SlidingImage_Adapter
Here's my SlidingImage_Adapter.class
public class SlidingImage_Adapter extends PagerAdapter {
private ArrayList<Pictures> IMAGES;
private LayoutInflater inflater;
private Context context;
public SlidingImage_Adapter(Context context,ArrayList<Pictures> IMAGES) {
this.context = context;
this.IMAGES=IMAGES;
inflater = LayoutInflater.from(context);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return IMAGES.size();
}
#Override
public Object instantiateItem(ViewGroup view, int position) {
View imageLayout = inflater.inflate(R.layout.slidingimage_layout, view, false);
assert imageLayout != null;
final ImageView imageView = (ImageView) imageLayout
.findViewById(R.id.image);
new DownloadImageTask(imageView).execute(IMAGES.get(position).getPhotopath());
// imageView.setImageResource(IMAGES.get(position));
view.addView(imageLayout, 0);
return imageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
notifyDataSetChanged();
}
#Override
public Parcelable saveState() {
return null;
}
and my AttractionInfo.class
public class AttractionInfo extends ActionBarActivity implements View.OnClickListener {
TextToSpeech tts;
TextView nameofplace,location,exact_address,operatinghours,info;
String nameofplace_s,location_s,exact_address_s,operatinghours_s,info_s,latlang_s,path_s,category_s;
ImageView play,rate,addtoplan,map;
ArrayList<Pictures> records;
private static ViewPager mPager;
private static int currentPage = 0;
String line=null;
private static int NUM_PAGES = 0;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attraction_info);
map = (ImageView)findViewById(R.id.map);
map.setOnClickListener(this);
records=new ArrayList<Pictures>();
nameofplace = (TextView) findViewById(R.id.nameofplace);
info = (TextView) findViewById(R.id.info);
exact_address = (TextView) findViewById(R.id.exact_address);
location = (TextView)findViewById(R.id.location);
operatinghours=(TextView)findViewById(R.id.operatinghours);
play = (ImageView) findViewById(R.id.play);
rate = (ImageView) findViewById(R.id.rate);
addtoplan = (ImageView)findViewById(R.id.addtoplan);
addtoplan.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
play.setOnClickListener(this);
rate.setOnClickListener(this);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
toolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
getSupportActionBar().setDisplayShowTitleEnabled(false);
tts = new TextToSpeech(AttractionInfo.this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR){
tts.setLanguage(Locale.ENGLISH);
}
}
});
if (extras != null) {
nameofplace_s = extras.getString("name");
nameofplace.setText(nameofplace_s);
info_s = extras.getString("description");
info.setText(info_s);
exact_address_s = extras.getString("exactaddress");
exact_address.setText(exact_address_s);
location_s = extras.getString("location");
location.setText(location_s);
operatinghours_s=extras.getString("operatinghours");
operatinghours.setText(operatinghours_s);
latlang_s = extras.getString("latlang");
path_s=extras.getString("path");
category_s = extras.getString("category");
}
}
public void onStart() {
super.onStart();
fetchphoto bt = new fetchphoto();
bt.execute();
}
#Override
protected void onPause() {
if (tts != null){
tts.stop();
tts.shutdown();
}
super.onPause();
}
#Override
public void onClick(View v) {
if (v == play) {
String speech1 = nameofplace.getText().toString();
String speech2 = info.getText().toString();
String speech = speech1 + "." + speech2;
tts.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
} else if (v==rate){
Intent myIntent = new Intent(this, ListOfReviews.class);
myIntent.putExtra("placename", nameofplace_s);
myIntent.putExtra("category",category_s);
startActivity(myIntent);
}else if(v==addtoplan){
Intent myIntent = new Intent(this, AddPlan.class);
myIntent.putExtra("placename", nameofplace_s);
myIntent.putExtra("category",category_s);
startActivity(myIntent);
}else if (v == map){
Intent myIntent = new Intent(this, Map.class);
myIntent.putExtra("placename", nameofplace_s);
myIntent.putExtra("category",category_s);
myIntent.putExtra("latlang",latlang_s);
myIntent.putExtra("address",exact_address_s);
myIntent.putExtra("path",path_s);
startActivity(myIntent);
}
}
private void init() {
SlidingImage_Adapter adapter = new SlidingImage_Adapter(this,records);
for(int i=0;i<records.size();i++){
Pictures pics = records.get(i);
String pic = pics.getPhotopath();
adapter.notifyDataSetChanged();
}
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(adapter);
CirclePageIndicator indicator = (CirclePageIndicator)
findViewById(R.id.indicator);
indicator.setViewPager(mPager);
final float density = getResources().getDisplayMetrics().density;
indicator.setRadius(5 * density);
NUM_PAGES =records.size();
// Auto start of viewpager
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == NUM_PAGES) {
currentPage = 0;
}
mPager.setCurrentItem(currentPage++, true);
}
};
Timer swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(Update);
}
},5000, 5000);
// Pager listener over indicator
indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
currentPage = position;
}
#Override
public void onPageScrolled(int pos, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int pos) {
}
});
}
private class fetchphoto extends AsyncTask<Void, Void, Void> {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
protected void onPreExecute() {
super.onPreExecute();
}
protected Void doInBackground(Void... params) {
InputStream is = null;
String result = "";
nameValuePairs.add(new BasicNameValuePair("cityname", nameofplace_s));
try
{
records.clear();
HttpParams httpParams = new BasicHttpParams();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://igph.esy.es/getphoto.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"utf-8"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
//parse json data
try {
Log.i("tagconvertstr", "["+result+"]");
// Remove unexpected characters that might be added to beginning of the string
result = result.substring(result.indexOf(""));
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Pictures p = new Pictures();
p.setPhotoname(json_data.getString("photo_name"));
p.setPlacename(json_data.getString("place_name"));
p.setCategory(json_data.getString("category"));
p.setPhotopath(json_data.getString("path"));
records.add(p);
}
} catch (Exception e) {
Log.e("ERROR", "Error pasting data " + e.toString());
}
return null;
}
protected void onPostExecute(Void result) {
// if (pd != null) pd.dismiss(); //close dialog
Log.e("size", records.size() + "");
init();
}
}
}
I've red some similar problems and learned that adding notifychanged may solved the problem but i dont where to place it. Hope you can help m . thanks

sent parameter to adapter in same class android

I have public class StudioDetail (main class) and in StudioDetail I generate private class SendfeedbackKelas like this :
private class SendfeedbackKelas extends AsyncTask<String, Void, String> {
private static final String LOG_TAG = "CariKelas";
Bundle extras = getIntent().getExtras();
final String token= extras.getString("TOKEN");
final String idstudio= extras.getString("STUDIO_ID");
#Override
protected String doInBackground(String... params) {
String date = params[0];
Utils.log("params 1:" + date);
// do above Server call here
kelasstudioList = new ArrayList<KelasStudioModel>();
String responseString = null;
final String url_kelas_studio = Constant.URI_BASE_STUDIO + idstudio + "/class" + "?date=" + date + "&token=" + token;
Utils.log("url kelas studio:"+ url_kelas_studio);
try
{
runOnUiThread(new Runnable() {
public void run() {
new JSONAsyncTask().execute(url_kelas_studio);
ListView listview = (ListView) findViewById(R.id.listView1);
adapter = new ClassSAdapter(context, R.layout.jadwalstudio_info, kelasstudioList);
listview.setAdapter(adapter);
}
});
}
catch (Exception e)
{
/*Toast.makeText(context,
"user not registered", Toast.LENGTH_SHORT).show();*/
Log.e(LOG_TAG, String.format("Error during login: %s", e.getMessage()));
}
return "processing";
}
protected void onPostExecute(Boolean result) {
//dialog.cancel();
}
}
that called ClassSAdapter like this :
private class ClassSAdapter extends ArrayAdapter<KelasStudioModel> {
final Context context = getContext();
ArrayList<KelasStudioModel> kelasstudioList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public ClassSAdapter(Context context, int resource, ArrayList<KelasStudioModel> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
kelasstudioList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View.OnClickListener listener1 = new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (int)v.getTag();
// do stuff based on position or kelasList.get(position)
// you can call mActivity.startActivity() if you need
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.setContentView(R.layout.dialog_popup_pesan_kelas);
closedialog = (ImageView) dialog.findViewById(R.id.closeDialog);
// if button is clicked, close the custom dialog
closedialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
/*studio_name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, StudioDetail.class);
startActivity(intent);
}
});*/
dialog.show();
}
};
View.OnClickListener listener2 = new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (int)v.getTag();
// do stuff based on position or kelasList.get(position)
// you can call mActivity.startActivity() if you need
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.setContentView(R.layout.dialog_popup_pelatih);
/*final String url_studio_image = Constant.URI_FRONTEND + "vendor_trainer/20150821052441-tanda-tanya.jpg";
Utils.log("url_studio_image: " + url_studio_image);
new DownloadImageTask((ImageView) dialog.findViewById(R.id.class_image_pelatih)).execute(url_studio_image);*/
closedialog = (ImageView) dialog.findViewById(R.id.closeDialog);
// if button is clicked, close the custom dialog
closedialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
};
// convert view = design
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.kelas = (TextView) v.findViewById(R.id.kelas);
holder.waktu = (TextView) v.findViewById(R.id.waktu);
holder.pelatih = (TextView) v.findViewById(R.id.pelatih);
// set OnClickListeners
holder.kelas.setOnClickListener(listener1);
holder.pelatih.setOnClickListener(listener2);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
//holder.imageview.setImageResource(R.drawable.promo_1);
holder.kelas.setText(kelasstudioList.get(position).getKelas());
holder.waktu.setText(kelasstudioList.get(position).getWaktu());
holder.pelatih.setText(kelasstudioList.get(position).getPelatih());
// set tags
holder.kelas.setTag(position);
holder.waktu.setTag(position);
holder.pelatih.setTag(position);
return v;
}
private class ViewHolder {
public TextView kelas;
public TextView waktu;
public TextView pelatih;
}
}
I want to sent some parameter like this from class JSONAsyncTask to private class ClassSAdapter on View.OnClickListener listener1 and View.OnClickListener listener2 :
final String startdate=object.getString("startdate");
final String masterclass_name=Html.fromHtml((String) object.getString("masterclass_name")).toString();
final String enddate=object.getString("enddate");
final String trainer_name=Html.fromHtml((String) object.getString("trainer_name")).toString();
How to sent that parameter?
As information here is JSONAsynTask class:
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
private static final String TAG_CLASSES = "classes";
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(context);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String responseAsText = EntityUtils.toString(entity);
Utils.log("daftar isi classes: " + responseAsText);
JSONObject jsonObj = new JSONObject(responseAsText);
// Getting JSON Array node
JSONArray classes = jsonObj.getJSONArray(TAG_CLASSES);
for(int i=0;i<classes.length();i++){
//HashMap<String, String> promo = new HashMap<String, String>();
JSONObject object = classes.getJSONObject(i);
final String startdate=object.getString("startdate");
final String masterclass_name=Html.fromHtml((String) object.getString("masterclass_name")).toString();
final String enddate=object.getString("enddate");
final String trainer_name=Html.fromHtml((String) object.getString("trainer_name")).toString();
KelasStudioModel actor = new KelasStudioModel();
String starttime = parseDateToHis((String) object.getString("startdate")).toString();
String endtime = parseDateToHis((String) object.getString("enddate")).toString();
actor.setKelas(Html.fromHtml((String) object.getString("masterclass_name")).toString());
actor.setWaktu(starttime + "-" + endtime);
actor.setPelatih(object.getString("trainer_name"));
kelasstudioList.add(actor);
}
return true;
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
if(result == false){
Toast.makeText(context, "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}else{
}
}
}
listener 1 and listener 2 called different dialog.

ListView onScroll add more items

private class getArticles extends AsyncTask<Void, Void, Void> {
String url;
getArticles(String paramUrl) {
this.url = paramUrl;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(App.this);
mProgressDialog.setMessage("Učitavanje artikala...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
arraylist = new ArrayList<>();
try {
Document document = Jsoup.connect(url).get();
Elements els = document.select("ul.category3 > li");
for (Element el : els) {
HashMap<String, String> map = new HashMap<>();
Elements slika = el.select("div.category3-image > a > img");
Elements naslov = el.select("div.category3-text > a.main-headline");
Element datum_noformat = el.select("div.category3-text > div.headlines-info > ul.headlines-info > li").first();
Element datum = datum_noformat.html(datum_noformat.html().replaceAll("Posted ", ""));
Elements desc = el.select("div.category3-text > p");
Elements link = el.select("div.category3-text > a.main-headline");
Element br_kom = el.select("div.category3-text > div.headlines-info > ul.headlines-info > li.comments-icon").first();
map.put("naslov", naslov.text());
map.put("datum", datum.text());
map.put("desc", desc.text());
map.put("ikona", slika.attr("src"));
map.put("link", link.attr("abs:href"));
map.put("brkom", br_kom.text());
arraylist.add(map);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
listview = (ListView) findViewById(R.id.listview);
adapter = new ArtikliAdapter(App.this, arraylist);
listview.setAdapter(adapter);
mProgressDialog.dismiss();
}
I searched for a lot of codes for onlistview scrolling, but didn't know how to implement it. The problem is, when I call my asynctask, I have an url param,
like new getArticles("http://example.com").execute();
I want to implement an onscrolllistener, but it goes like this, my param is usually set to: http://www.example.com/category/categoryname/, so the second page goes like http://www.example.com/category/categoryname/page/2/, the third one goes http://www.example.com/category/categoryname/page/3/ and so on. Each page has got 7 items that need to be parsed.
How could I implement onscrolllistener, because of the url param?
Thanks in advance.
Base on this link, I have written following solution to add elements ( 30 elements at a time, i.e page size = 30) to listview asynchronously.
Create a class named EndlessListView as follows:
public class EndlessListView extends ListView implements OnScrollListener {
private View footer;
private boolean isLoading;
private EndlessListener listener;// listner
private EndlessAdapter endlessAdapter;// adapter.
private int maxNoOfElement;
public EndlessListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.setOnScrollListener(this);
}
public EndlessListView(Context context, AttributeSet attrs) {
super(context, attrs);
this.setOnScrollListener(this);
}
public EndlessListView(Context context) {
super(context);
this.setOnScrollListener(this);
}
public void setListener(EndlessListener listener) {
this.listener = listener;
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (getAdapter() == null)
return;
if (getAdapter().getCount() == 0 || getAdapter().getCount() <= 5)
return;
int l = visibleItemCount + firstVisibleItem;
if (l >= totalItemCount && !isLoading) {
// It is time to add new data. We call the listener
Log.e("LOAD", "DATA");
isLoading = true;
listener.loadData();
}
}
public void setMaxElemnt(int maxNoOfElement) {
this.maxNoOfElement = maxNoOfElement;
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
public void setLoadingView(int resId) {
LayoutInflater inflater = (LayoutInflater) super.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
footer = (View) inflater.inflate(resId, null);
this.addFooterView(footer);
}
public void setAdapter(EndlessAdapter adapter) {
super.setAdapter(adapter);
this.endlessAdapter = adapter;
}
public void addNewData(List<Integer> data) {
endlessAdapter.setData(data);
endlessAdapter.notifyDataSetChanged();
isLoading = false;
}
public static interface EndlessListener {
public void loadData();
}
}
After this we have to create the adapter for it,called
EndlessAdapter
public class EndlessAdapter extends BaseAdapter {
private List<Integer> mIntegers;
private Context context;
public EndlessAdapter(Context context) {
this.context = context;
}
public void setData(List<Integer> mIntegers) {
this.mIntegers = mIntegers;
}
#Override
public int getCount() {
if (mIntegers == null)
return 0;
return mIntegers.size();
}
#Override
public Integer getItem(int index) {
if (mIntegers == null) {
return null;
} else {
return mIntegers.get(index);
}
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
class ViewHolder {
TextView textView;
}
#Override
public View getView(int index, View view, ViewGroup viewGroup) {
ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = ((LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(R.layout.rows, viewGroup, false);
holder.textView = (TextView) view.findViewById(R.id.mtext);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.textView.setText(getItem(index) + "");
return view;
}
}
Now in xml of the activity we could use EndlessListView(in com.example.stackoverflow package) as follows :
<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" >
<com.example.stackoverflow.EndlessListView
android:id="#+id/endlessListView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
After this step we need to make following change in the MainActivity
public class MainActivity extends Activity implements EndlessListener {
private EndlessAdapter adapter;
private EndlessListView endlessListView;
private List<Integer> data;
private int gStartIndex = 30;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
endlessListView = (EndlessListView) findViewById(R.id.endlessListView);
adapter = new EndlessAdapter(this);
data = new ArrayList<Integer>();
endlessListView.setLoadingView(R.layout.footer);
// endlessListView.showFooter();
endlessListView.setListener(this);
endlessListView.setAdapter(adapter);
gStartIndex = 0;
fillData(gStartIndex);
}
private void fillData(int startIndex) {
new AsyncLoadData().execute(startIndex);
}
#Override
public void loadData() {
fillData(gStartIndex);
}
private class AsyncLoadData extends AsyncTask<Integer, Integer, Void> {
#Override
protected Void doInBackground(Integer... params) {
int gendIndex = params[0] + 30;
gStartIndex = gendIndex;
/***
* Here you could add your n/w code. To simulate the n/w comm. i am
* adding elements to list and making it sleep for few sec.
* */
for (int i = params[0]; i < gendIndex; i++) {
publishProgress(i);
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
data.add(values[0]);
}
#Override
protected void onPostExecute(Void result) {
endlessListView.addNewData(data);
}
}
}
This custom ScrollListView that I just found has OnBottomReachedListener which you can implement from your Activity or Fragment and receive events when user hits the bottom of the page. You would also need to track the current page and when bottom is hit to download the next page. The latest data should be added to your existing ArrayList and you should call notifyDataSetChanged() on your adapter so ListView can render the new data. You don't have to create new adapter, you just need to update the data source which is your ArrayList.
If you support orientation change you would must to save in onSaveInstanceState() your current page number so when Activity or Fragment is recreated it can continue from correct page. And you would have to keep the ArrayList data source safe of configuration changes because you don't want to downloaded it again. I would suggest using the Fragment with setRetainInstance() set to true to persist ArrayList.
Here is my custom code for keeping data around using RetainFragment:
/**
* A simple non-UI Fragment that stores a single Object
* and is retained over configuration changes.
*/
public class RetainFragment<E extends Object> extends Fragment {
/** Object for retaining. */
private E mObject;
/**
* Empty constructor as per the Fragment documentation
*/
public RetainFragment() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Make sure this Fragment is retained over a configuration change
setRetainInstance(true);
}
/**
* Store a single object in this Fragment.
*
* #param object The object to store
*/
public void setObject(E object) {
mObject = object;
}
/**
* Get the stored object.
*
* #return The stored object
*/
public E getObject() {
return mObject;
}
}
Example of RetainFragment usage in your Activity:
FragmentManager fm = getFragmentManager();
mRetainFragment = (RetainFragment<ArrayList>) fm.findFragmentByTag(RETAIN_FRAG);
if (mRetainFragment == null) {
mRetainFragment = new RetainFragment<>();
mRetainFragment.setObject(new ArrayList());
fm.beginTransaction().add(mRetainFragment, RETAIN_FRAG).commit();
}
ArrayList yourArrayList = mRetainFragment.getObject();
// Now your ArrayList is saved accrossed configuration changes
here what you want fist add onscrolllistner to listview
boolean loading_flage = false;
yourlistview.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(
AbsListView view,
int scrollState) {
// TODO Auto-generated method stub
}
#Override
public void onScroll(AbsListView view,
int firstVisibleItem,
int visibleItemCount,
int totalItemCount) {
final int lastItem = firstVisibleItem
+ visibleItemCount;
if ((lastItem == totalItemCount)
& loading_flage == false) {
//this to prevent the list to make more than one request in time
loading_flage = true;
//you can put the index for your next page here
loadMore(int page);
}
}
});
and then in loading more after loading the page set the loading with false and parse the data add it to the data that you aleardy have
//notify the adapter
adapter.notifyDataSetChanged();
loading_flage = false;
You can achieve by adding the scrolllistener on listview and check condition if list last visible item is last in ArrayList then call the asynctask with incremented page number and update the listview,mean while add the view on listview and after getting the result from server remove the loading more view from the listview like this -
AndroidListViewLoadMoreActivity.java
public class AndroidListViewLoadMoreActivity extends Activity {
ArrayList<Country> countryList;
MyCustomAdapter dataAdapter = null;
int page = 0;
boolean loadingMore = false;
View loadMoreView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView listView = (ListView) findViewById(R.id.listView1);
loadMoreView = ((LayoutInflater)this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(R.layout.loadmore, null, false);
listView.addFooterView(loadMoreView);
//create an ArrayAdaptar from the String Array
countryList = new ArrayList<Country>();
dataAdapter = new MyCustomAdapter(this,
R.layout.country_info, countryList);
listView.setAdapter(dataAdapter);
//enables filtering for the contents of the given ListView
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Country country = (Country) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),
country.getCode(), Toast.LENGTH_SHORT).show();
}
});
listView.setOnScrollListener(new OnScrollListener(){
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if((lastInScreen == totalItemCount) && !(loadingMore)){
String url = "http://10.0.2.2:8080/CountryWebService" +
"/CountryServlet";
grabURL(url);
}
}
});
String url = "http://example.com";
grabURL(url);
}
public void grabURL(String url) {
Log.v("Android Spinner JSON Data Activity", url);
new GrabURL().execute(url);
}
private class GrabURL extends AsyncTask<String, Void, String> {
private static final int REGISTRATION_TIMEOUT = 3 * 1000;
private static final int WAIT_TIMEOUT = 30 * 1000;
private final HttpClient httpclient = new DefaultHttpClient();
final HttpParams params = httpclient.getParams();
HttpResponse response;
private String content = null;
private boolean error = false;
private ProgressDialog dialog =
new ProgressDialog(AndroidListViewLoadMoreActivity.this);
protected void onPreExecute() {
dialog.setMessage("Getting your data... Please wait...");
dialog.show();
}
protected String doInBackground(String... urls) {
String URL = null;
loadingMore = true;
try {
URL = urls[0];
HttpConnectionParams.setConnectionTimeout(params, REGISTRATION_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, WAIT_TIMEOUT);
ConnManagerParams.setTimeout(params, WAIT_TIMEOUT);
HttpPost httpPost = new HttpPost(URL);
//add name value pair for the country code
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("page",String.valueOf(page)));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
content = out.toString();
} else{
//Closes the connection.
Log.w("HTTP1:",statusLine.getReasonPhrase());
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
Log.w("HTTP2:",e );
content = e.getMessage();
error = true;
cancel(true);
} catch (IOException e) {
Log.w("HTTP3:",e );
content = e.getMessage();
error = true;
cancel(true);
}catch (Exception e) {
Log.w("HTTP4:",e );
content = e.getMessage();
error = true;
cancel(true);
}
return content;
}
protected void onCancelled() {
dialog.dismiss();
Toast toast = Toast.makeText(AndroidListViewLoadMoreActivity.this,
"Error connecting to Server", Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP, 25, 400);
toast.show();
}
protected void onPostExecute(String content) {
dialog.dismiss();
Toast toast;
if (error) {
toast = Toast.makeText(AndroidListViewLoadMoreActivity.this,
content, Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP, 25, 400);
toast.show();
} else {
displayCountryList(content);
}
}
}
private void displayCountryList(String response){
JSONObject responseObj = null;
try {
Gson gson = new Gson();
responseObj = new JSONObject(response);
JSONArray countryListObj = responseObj.getJSONArray("countryList");
//countryList = new ArrayList<Country>();
if(countryListObj.length() == 0){
ListView listView = (ListView) findViewById(R.id.listView1);
listView.removeFooterView(loadMoreView);
}
else {
for (int i=0; i<countryListObj.length(); i++){
//get the country information JSON object
String countryInfo = countryListObj.getJSONObject(i).toString();
//create java object from the JSON object
Country country = gson.fromJson(countryInfo, Country.class);
//add to country array list
countryList.add(country);
dataAdapter.add(country);
}
page++;
dataAdapter.notifyDataSetChanged();
loadingMore = false;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Make MyCustomAdapter.java as adapter
private class MyCustomAdapter extends ArrayAdapter<Country> {
private ArrayList<Country> countryList;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Country> countryList) {
super(context, textViewResourceId, countryList);
this.countryList = new ArrayList<Country>();
this.countryList.addAll(countryList);
}
private class ViewHolder {
TextView code;
TextView name;
TextView continent;
TextView region;
}
public void add(Country country){
Log.v("AddView", country.getCode());
this.countryList.add(country);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.country_info, null);
holder = new ViewHolder();
holder.code = (TextView) convertView.findViewById(R.id.code);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.continent = (TextView) convertView.findViewById(R.id.continent);
holder.region = (TextView) convertView.findViewById(R.id.region);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Country country = this.countryList.get(position);
holder.code.setText(country.getCode());
holder.name.setText(country.getName());
holder.continent.setText(country.getContinent());
holder.region.setText(country.getRegion());
return convertView;
}
}
}
Create Country.Java as pojo -
public class Country {
String code = null;
String name = null;
String continent = null;
String region = null;
Double lifeExpectancy = null;
Double gnp = null;
Double surfaceArea = null;
int population = 0;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContinent() {
return continent;
}
public void setContinent(String continent) {
this.continent = continent;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public Double getLifeExpectancy() {
return lifeExpectancy;
}
public void setLifeExpectancy(Double lifeExpectancy) {
this.lifeExpectancy = lifeExpectancy;
}
public Double getGnp() {
return gnp;
}
public void setGnp(Double gnp) {
this.gnp = gnp;
}
public Double getSurfaceArea() {
return surfaceArea;
}
public void setSurfaceArea(Double surfaceArea) {
this.surfaceArea = surfaceArea;
}
public int getPopulation() {
return population;
}
public void setPopulation(int population) {
this.population = population;
}
}
Create main.xml for main layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="vertical">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:padding="10dp"
android:text="#string/some_text" android:textSize="20sp" />
<ListView android:id="#+id/listView1" android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
Create country_info.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="6dip" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Code: "
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:text="Name: "
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView2"
android:layout_below="#+id/textView2"
android:text="Continent: "
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView3"
android:layout_below="#+id/textView3"
android:text="Region: "
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/continent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView3"
android:layout_alignBottom="#+id/textView3"
android:layout_toRightOf="#+id/textView3"
android:text="TextView" />
<TextView
android:id="#+id/region"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView4"
android:layout_alignBottom="#+id/textView4"
android:layout_alignLeft="#+id/continent"
android:text="TextView" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView3"
android:layout_toRightOf="#+id/textView3"
android:text="TextView" />
<TextView
android:id="#+id/code"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView2"
android:layout_alignLeft="#+id/name"
android:text="TextView" />
</RelativeLayout>
Footer View Text - loadmore.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:gravity="center_horizontal"
android:padding="3dp"
android:layout_height="fill_parent">
<TextView
android:id="#id/android:empty"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center"
android:padding="5dp"
android:text="Loading more data..."/>
</LinearLayout>
Don't forget to mention internet permission with -
<uses-permission android:name="android.permission.INTERNET" />
First, you need a OnScrollListener method like this:
private OnScrollListener onScrollListener() {
return new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
int threshold = 1;
int count = listView.getCount();
if (scrollState == SCROLL_STATE_IDLE) {
if (listView.getLastVisiblePosition() >= count - threshold && pageCount < 2) {
Log.i(TAG, "loading more data");
// Execute LoadMoreDataTask AsyncTask
//It reached ListView bottom
getDataFromUrl(url_page2);
}
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
}
};
}
set List View scroll listener by listView.setOnScrollListener(onScrollListener());
I have a full tutorial post HERE! You can visit it!

Categories

Resources