Skip to content
Merged

V1 #1

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions ListViewExample/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,17 @@ android {
}
}

repositories {
mavenCentral()
}

dependencies {
implementation 'org.slf4j:slf4j-api:1.7.25'
implementation 'ch.qos.logback:logback-classic:1.0.9'
implementation 'ch.qos.logback:logback-core:1.0.9'
implementation 'com.fasterxml.jackson.core:jackson-databind:2.7.0'
implementation 'org.projectlombok:lombok:1.18.4'
annotationProcessor 'org.projectlombok:lombok:1.18.4'
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
Expand Down
1 change: 1 addition & 0 deletions ListViewExample/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,5 @@
</activity>
</application>

<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
Original file line number Diff line number Diff line change
@@ -1,20 +1,114 @@
package com.loot.markhardwick.listviewexample;

import android.support.v7.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.loot.markhardwick.listviewexample.ui.main.MainFragment;
import com.loot.markhardwick.listviewexample.backend.main.Fetcher;
import com.loot.markhardwick.listviewexample.backend.main.User;

public class MainActivity extends AppCompatActivity {
public class MainActivity extends Activity {
ListAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, MainFragment.newInstance())
.commitNow();

ListView listView = findViewById(R.id.listView);
ProgressBar progressBar = findViewById(R.id.progressBar);
listView.setEmptyView(progressBar);

adapter = new ListAdapter(this, Fetcher.getUsers());
listView.setAdapter(adapter);

/* Not needed for task will flesh out later
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

}
});
*/

Fetcher fetcher = new Fetcher(new Fetcher.FetcherResponse() {
@Override
public void processFinish(User[] newUserList) {
adapter.updateUsers(newUserList);
}
});
fetcher.execute();
}

private class ListAdapter extends BaseAdapter {
Context context;
User[] users;
private LayoutInflater inflater;

ListAdapter(Context context, User[] users) {
this.context = context;
this.users = users;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

void updateUsers(User[] newUsers){
users = newUsers;
this.notifyDataSetChanged();
}

@Override
public int getCount() {
return users.length;
}

@Override
public Object getItem(int position) {
return users[position];
}

@Override
public long getItemId(int position) {
return position;
}

@SuppressLint("DefaultLocale")
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View toReturn = convertView;
if(toReturn == null){
toReturn = inflater.inflate(R.layout.row_just_name, null);
}
User user = users[position];
TextView nameField = toReturn.findViewById(R.id.name);
nameField.setText(String.format("%s", user.getName()));

/* Reread task was only for name and surname
TextView idField = toReturn.findViewById(R.id.idNumber);
idField.setText(String.format("%s%d", getString(R.string.id), user.getId()));
TextView usernameField = toReturn.findViewById(R.id.username);
usernameField.setText(String.format("%s%s", getString(R.string.username), user.getUsername()));
TextView emailField = toReturn.findViewById(R.id.email);
emailField.setText(String.format("%s%s", getString(R.string.email), user.getEmail()));
TextView addressField = toReturn.findViewById(R.id.address);
addressField.setText(String.format("%s%s", getString(R.string.address), user.getAddress().toString()));
TextView phoneField = toReturn.findViewById(R.id.phone);
phoneField.setText(String.format("%s%s", getString(R.string.phone), user.getPhone()));
TextView websiteField = toReturn.findViewById(R.id.website);
websiteField.setText(String.format("%s%s", getString(R.string.website), user.getWebsite()));
TextView companyField = toReturn.findViewById(R.id.company);
companyField.setText(String.format("%s%s", getString(R.string.company), user.getCompany().toString()));
*/
return toReturn;
}
}
}


Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package com.loot.markhardwick.listviewexample.backend.main;

import android.os.AsyncTask;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;

import lombok.extern.slf4j.Slf4j;

/**
* Class to grab json array of users from:
* https://jsonplaceholder.typicode.com/users
* and turn response into an array of objects
*/

@Slf4j
public class Fetcher extends AsyncTask<Void, Void, User[]> {
static User[] users = new User[0];
private FetcherResponse delegate;

public Fetcher(FetcherResponse delegate){
this.delegate = delegate;
}

static void fetchUsers() {
log.debug("fetchUsers() called");
URL url;
HttpURLConnection con;
try {
String urlAddress = "https://jsonplaceholder.typicode.com/users";
url = new URL(urlAddress);
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type", "application/json");
int status = con.getResponseCode();
log.debug("Http Response Code: {}", status);
if (getBaseResponseCode(status) == 2){
InputStream inputStream = con.getInputStream();
handleResponse(inputStream);
} else {
log.error("Http Error Code: {}", status);
}
} catch (java.io.IOException e) {
log.error(e.getMessage());
log.error(Arrays.toString(e.getStackTrace()));
}
}

private static void handleResponse(InputStream inputStream){
log.debug("handleResponse() called");
ObjectMapper mapper = new ObjectMapper();
try {
users = mapper.readValue(inputStream, User[].class);
log.debug("New contents of Users:");
log.debug(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(users));
log.debug("Successful response handle");
} catch (IOException e) {
log.error(e.getMessage());
log.error(Arrays.toString(e.getStackTrace()));
}
}

private static int getBaseResponseCode(int x) {
while (x > 10) {
x = x / 10;
}
return x;
}

public static User[] getUsers(){
return users;
}

@Override
protected User[] doInBackground(Void ... voids) {
fetchUsers();
return users;
}

@Override
protected void onPostExecute(User[] result) {
delegate.processFinish(result);
}

public interface FetcherResponse {
void processFinish(User[] newUserList);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package com.loot.markhardwick.listviewexample.backend.main;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

/**
* POJO for jackson deserialization of users
*/

@Setter @Getter
@AllArgsConstructor
@NoArgsConstructor
@Slf4j
public class User {
int id;
String name, username, email, phone, website;
Address address;
Company company;

@ToString
@Setter @Getter
@AllArgsConstructor
@NoArgsConstructor
public class Address {
String street, suite, city, zipcode;
Geo geo;

@ToString
@Setter @Getter
@AllArgsConstructor
@NoArgsConstructor
public class Geo {
String lat, lng;
}
}

@ToString
@Setter @Getter
@AllArgsConstructor
@NoArgsConstructor
public class Company {
String name, catchPhrase, bs;
}
}

This file was deleted.

This file was deleted.

47 changes: 45 additions & 2 deletions ListViewExample/app/src/main/res/layout/main_activity.xml
Original file line number Diff line number Diff line change
@@ -1,7 +1,50 @@
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" />
tools:context=".MainActivity"
>

<Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/header"
android:textSize="22sp"
android:textColor="@color/white"
android:textStyle="bold"
/>

</Toolbar>

<ListView
android:id="@+id/listView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
app:layout_constraintTop_toBottomOf="@+id/toolbar"
/>

<ProgressBar
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:indeterminate="true"
android:indeterminateTint="@color/colorAccent2"
android:visibility="invisible"
/>
</android.support.constraint.ConstraintLayout>
Loading