Android ListView Layout with Custom Data

activity_main.xml

[code lang=”xml”]
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.rekadia.simpleapps.HttpExampleActivity" >

<!–<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"–>
<!–xmlns:tools="http://schemas.android.com/tools"–>
<!–android:layout_width="match_parent"–>
<!–android:layout_height="wrap_content"–>
<!–tools:context="com.rekadia.simpleapps.HttpExampleActivity"–>
<!–android:orientation="horizontal" >–>
<!–<EditText android:id="@+id/myUrl"–>
<!–android:layout_weight="1"–>
<!–android:layout_width="0dp"–>
<!–android:layout_height="wrap_content"–>
<!–android:hint="@string/myUrl" />–>

<!–<Button–>
<!–android:layout_width="wrap_content"–>
<!–android:layout_height="wrap_content"–>
<!–android:text="@string/button_fetch"–>
<!–android:onClick="myClickHandler" />–>

<!–</LinearLayout>–>

<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/swipe_container"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<ListView
android:id="@+id/list"
android:fadingEdge="vertical"
android:fadingEdgeLength="10dp"
android:longClickable="true"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>

</android.support.v4.widget.SwipeRefreshLayout>

<TextView
android:id="@+id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Loading feed data…" />

</RelativeLayout>
[/code]

custom_list_view.xml
[code lang=”xml”]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/thumbnail"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="1dp"
android:layout_marginTop="1dp"
android:src="@drawable/ic_launcher" />

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:id="@+id/name"
android:textSize="14sp"
android:textStyle="bold"
android:textColor="@color/abc_search_url_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView android:id="@+id/address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView android:id="@+id/city"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>

</LinearLayout>
[/code]

MainActivity.java
[code lang=”java”]
package com.rekadia.databaseexample;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.rekadia.databaseexample.adapters.SPBGListViewAdapter;
import com.rekadia.databaseexample.json.SPBGJson;
import com.rekadia.databaseexample.models.SPBG;
import com.rekadia.databaseexample.models.ServiceList;
import com.rekadia.databaseexample.sql.SPBGContract;
import com.rekadia.databaseexample.sql.SPBGDbHelper;

import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends ActionBarActivity implements SwipeRefreshLayout.OnRefreshListener {
private static final String DEBUG_TAG = "HttpExample";
private TextView textEmpty;
private ListView lv1;
private SPBGListViewAdapter spbgAdapter;
private SwipeRefreshLayout swipeLayout;
private SPBGJson jsonReader;
private Toast toast;
private SPBGDbHelper dbHelper;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorSchemeResources(android.R.color.holo_blue_light,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);

//urlText = (EditText) findViewById(R.id.myUrl);
lv1 = (ListView) findViewById(R.id.list);
lv1.setEmptyView(findViewById(R.id.empty));
spbgAdapter = new SPBGListViewAdapter(this);
lv1.setAdapter(spbgAdapter);

jsonReader = new SPBGJson(getApplicationContext());
dbHelper = new SPBGDbHelper(getApplicationContext());

//c.moveToFirst();
ServiceList serviceList = readFromDb();

try {
spbgAdapter.setList(serviceList.data);
} catch (Exception e) {

}

// fileStorage = new FileStorage("SPBGData");
// String data = fileStorage.load(this);
// try {
// ServiceList serviceList = parseJSONString(data);
// spbgAdapter.setList(serviceList.data);
// } catch (Exception e) {
//
// }

Toast toast = Toast.makeText(getApplicationContext(), "Unable to retrieve web page. URL may be invalid.", Toast.LENGTH_LONG);
}

@Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
connectToSPBG("");
}
}, 5000);
}

// When user clicks button, calls AsyncTask.
// Before attempting to fetch the URL, makes sure that there is a network connection.
public void myClickHandler(View view) {
// Gets the URL from the UI’s text field.
String stringUrl = "";//urlText.getText().toString();
connectToSPBG(stringUrl);
}

public void connectToSPBG(String url) {
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new DownloadWebpageTask(spbgAdapter).execute(url);
} else {
toast = Toast.makeText(getApplicationContext(), "No network connection available.", Toast.LENGTH_SHORT);
toast.show();
swipeLayout.setRefreshing(false);
//textView.setText("No network connection available.");
}
}

// Uses AsyncTask to create a task away from the main UI thread. This task takes a
// URL string and uses it to create an HttpUrlConnection. Once the connection
// has been established, the AsyncTask downloads the contents of the webpage as
// an InputStream. Finally, the InputStream is converted into a string, which is
// displayed in the UI by the AsyncTask’s onPostExecute method.
private class DownloadWebpageTask extends AsyncTask<String, Void, ServiceList> {

private final SPBGListViewAdapter mAdapter;
public DownloadWebpageTask(SPBGListViewAdapter spbgAdapter) {
mAdapter = spbgAdapter;
toast = Toast.makeText(getApplicationContext(), "Unable to retrieve web page. URL may be invalid.", Toast.LENGTH_SHORT);
}

@Override
protected ServiceList doInBackground(String… urls) {

// params comes from the execute() call: params[0] is the url.
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
toast.show();
swipeLayout.setRefreshing(false);
return new ServiceList();
} catch (JSONException e) {
toast.show();
swipeLayout.setRefreshing(false);
return new ServiceList();
}
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(ServiceList result) {
spbgAdapter.setList(result.data);
swipeLayout.setRefreshing(false);
}
}

// Given a URL, establishes an HttpUrlConnection and retrieves
// the web page content as a InputStream, which it returns as
// a string.
private ServiceList downloadUrl(String myurl) throws IOException, JSONException {
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500;
String myUrl = "http://rekadia.net:14523/CNG/api/spbg/listspbg";
try {
URL url = new URL(myUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d(DEBUG_TAG, "The response is: " + response);
is = conn.getInputStream();

// Convert the InputStream into a string
//String contentAsString = readIt(is, len);
ServiceList searchResults = readJsonStream(is);
return searchResults;

// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}

public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
StringBuilder data = new StringBuilder();
reader = new InputStreamReader(stream, "UTF-8");
int ch = 0;
while ( (ch = reader.read()) != -1) {
//do your processing here…
data.append((char)ch);
}

Log.d(DEBUG_TAG, "The string is: " + data.toString());
return data.toString();
}

public ServiceList readJsonStream(InputStream stream) throws IOException, JSONException {
Reader reader = null;
StringBuilder data = new StringBuilder();
reader = new InputStreamReader(stream, "UTF-8");
int ch = 0;
while ( (ch = reader.read()) != -1) {
//do your processing here…
data.append((char)ch);
}
reader.close();
Log.d(DEBUG_TAG, "The string is: " + data.toString());
//fileStorage.save(this,data.toString());
ServiceList result = jsonReader.parseJSONString(data.toString());
writeToDb(result);
return result;
}

public ServiceList readFromDb() {
// retrieve data
SQLiteDatabase db = dbHelper.getReadableDatabase();

// Define a projection that specifies which columns from the database
// you will actually use after this query.
String[] projection = {
SPBGContract.SPBG._ID,
SPBGContract.SPBG.COLUMN_NAME_ID,
SPBGContract.SPBG.COLUMN_NAME_NAME,
SPBGContract.SPBG.COLUMN_NAME_ADDRESS,
SPBGContract.SPBG.COLUMN_NAME_CITY,
SPBGContract.SPBG.COLUMN_NAME_IMAGE_NAME
};

// How you want the results sorted in the resulting Cursor
String sortOrder =
SPBGContract.SPBG.COLUMN_NAME_NAME + " ASC";

Cursor c = db.query(
SPBGContract.SPBG.TABLE_NAME, // The table to query
projection, // The columns to return
null, // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // don’t group the rows
null, // don’t filter by row groups
sortOrder // The sort order
);

ServiceList serviceList = new ServiceList();
serviceList.total = 0;
serviceList.data = new ArrayList();
while(c.moveToNext()) {
SPBG spbg = new SPBG();
spbg.address = c.getString(c.getColumnIndexOrThrow(SPBGContract.SPBG.COLUMN_NAME_ADDRESS));
spbg.name = c.getString(c.getColumnIndexOrThrow(SPBGContract.SPBG.COLUMN_NAME_NAME));
spbg.city = c.getString(c.getColumnIndexOrThrow(SPBGContract.SPBG.COLUMN_NAME_CITY));
spbg.imageUrl = c.getString(c.getColumnIndexOrThrow(SPBGContract.SPBG.COLUMN_NAME_IMAGE_NAME));
serviceList.data.add(spbg);
}

return serviceList;
}

public void writeToDb(ServiceList serviceList) {
// Gets the data repository in write mode
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.delete(SPBGContract.SPBG.TABLE_NAME, null, null);
for (SPBG spbgData : (List<SPBG>)serviceList.data){
// Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
values.put(SPBGContract.SPBG.COLUMN_NAME_ID, spbgData.id);
values.put(SPBGContract.SPBG.COLUMN_NAME_NAME, spbgData.name);
values.put(SPBGContract.SPBG.COLUMN_NAME_ADDRESS, spbgData.address);
values.put(SPBGContract.SPBG.COLUMN_NAME_CITY, spbgData.city);
values.put(SPBGContract.SPBG.COLUMN_NAME_IMAGE_NAME, spbgData.imageUrl);

// Insert the new row, returning the primary key value of the new row
long newRowId;
newRowId = db.insert(
SPBGContract.SPBG.TABLE_NAME,
null,
values);
}
}
}
[/code]

CustomListViewAdapter.java
[code lang=”java”]
package com.rekadia.databaseexample.adapters;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.test.RenamingDelegatingContext;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.rekadia.databaseexample.R;
import com.rekadia.databaseexample.imageFile.ImageFileStorage;
import com.rekadia.databaseexample.models.IServiceModel;
import com.rekadia.databaseexample.models.SPBG;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

/**
* Created by Septu Jamasok on 3/5/2015.
*/
public class SPBGListViewAdapter extends BaseAdapter {
private static final String DEBUG_TAG = "HttpExample";
private static List<SPBG> searchArrayList;
private ImageFileStorage imageFileStorage;
private Context context;

private LayoutInflater mInflater;

public SPBGListViewAdapter(Context context) {
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
searchArrayList = new ArrayList<>();
imageFileStorage = new ImageFileStorage();
this.context = context;
}

public int getCount() {
return searchArrayList.size();
}

public Object getItem(int position) {
return searchArrayList.get(position);
}

public void setList(List data) {
searchArrayList = (List<SPBG>)data;
notifyDataSetChanged();
}

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

public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
//if (convertView == null) {
Log.d("imageName","test");
convertView = mInflater.inflate(R.layout.custom_list_view, null);
holder = new ViewHolder();
holder.imgThumbnail = (ImageView) convertView.findViewById(R.id.thumbnail);
holder.txtName = (TextView) convertView.findViewById(R.id.name);
holder.txtAddress = (TextView) convertView.findViewById(R.id.address);
holder.txtCity = (TextView) convertView.findViewById(R.id.city);

convertView.setTag(holder);
//} else {
//holder = (ViewHolder) convertView.getTag();
//Log.d("holder",holder.toString());
//}
try {
String imageName = searchArrayList.get(position).imageUrl;
Log.d("imageName",position + " " + imageName);
if (imageName != "") {
Bitmap bmp = imageFileStorage.loadImageFromFile(context, searchArrayList.get(position).imageUrl);
holder.imgThumbnail.setImageBitmap(bmp);
Log.d("imageName",holder.imgThumbnail.toString());
} else {
holder.imgThumbnail.setImageResource(R.drawable.ic_launcher);
}
} catch (IOException e) {
// do nothing
}

holder.txtName.setText(searchArrayList.get(position).name);
holder.txtAddress.setText(searchArrayList.get(position).address);
holder.txtCity.setText(searchArrayList.get(position).city);

return convertView;
}

static class ViewHolder {
TextView txtName;
TextView txtAddress;
TextView txtCity;
ImageView imgThumbnail;
}
}
[/code]

Septu Jamasoka has written 23 articles

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>