Skip to content

Instantly share code, notes, and snippets.

@francisrod01
Last active May 8, 2020 13:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save francisrod01/54c3ff6b8af547b71161 to your computer and use it in GitHub Desktop.
Save francisrod01/54c3ff6b8af547b71161 to your computer and use it in GitHub Desktop.
[Help] Android - Convert JSON object for ArrayAdapter and ListView object
public class HttpClientFactory {
private HttpClient client;
private HttpPost httpPost;
private HttpGet httpGet;
private String responseBody;
public JSONObject sendGet(String url) {
client = new DefaultHttpClient();
httpGet = new HttpGet(Extras.BASE_URL + Extras.BASE_API + url);
try {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
responseBody = client.execute(httpGet, responseHandler);
if (isJson(responseBody)) {
return new JSONObject(responseBody);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
private boolean isJson(String str) {
try {
new JSONObject(str);
} catch (JSONException e) {
try {
new JSONArray(str);
} catch (JSONException e1) {
return false;
}
}
return true;
}
}
{
"content": [
{
"id": 1,
"title": "Item 1",
"children": []
},
{
"id": 2,
"title": "Item 2",
"children": []
},
{
"id": 3,
"title": "Item 3",
"children": []
},
],
"api_version": 1
}
public class Product {
int id;
String title;
ArrayList children;
public Product(JSONObject object) {
try {
this.id = object.getInt("id");
this.title = object.getString("title");
} catch (JSONException e) {
e.printStackTrace();
}
}
public static ArrayList<Product> fromJson(JSONArray jsonObjects) {
ArrayList<Product> products = new ArrayList<Product>();
for (int i = 0; i < jsonObjects.length(); i++) {
try {
products.add(new Product(jsonObjects.getJSONObject(i)));
} catch (JSONException e) {
e.printStackTrace();
}
}
return products;
}
public ArrayList getChildren() {
return children;
}
public void setChildren(ArrayList children) {
this.children = children;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public String toString() {
return id + " - " + title;
}
}
public class ProductAdapter extends ArrayAdapter<Product> {
private List<Product> productList;
private Context context;
public ProductAdapter(List<Product> productList, Context ctx) {
super(ctx, R.layout.row_layout, productList);
this.productList = productList;
this.context = ctx;
}
public int getCount() {
if (productList != null)
return productList.size();
return 0;
}
public Product getItem(int position) {
if (productList != null)
return productList.get(position);
return null;
}
public long getItemId(int position) {
if (productList != null)
return productList.get(position).hashCode();
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// row_layout.xml file for list items
convertView = inflater.inflate(R.layout.row_layout, parent, false);
}
Product product = productList.get(position);
TextView textId = (TextView) convertView.findViewById(R.id.id);
textId.setText(product.getId());
TextView textTitle = (TextView) convertView.findViewById(R.id.title);
textTitle.setText(product.getTitle());
return convertView;
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:showIn="@layout/activity_main"
tools:context=".MainActivity"
android:orientation="vertical"
>
<ListView
android:id="@+id/custom_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
></ListView>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/id"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:textStyle="bold"
/>
<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="8dp"
android:textStyle="italic"
/>
</LinearLayout>
/**
* MainActivity class
*/
public class StudentsListActivity extends AppCompatActivity {
private ListView list;
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mTextView = (TextView) findViewById(R.id.text);
list = (ListView) findViewById(R.id.custom_list);
}
@Override
protected void onResume() {
super.onResume();
AsyncTask<Void, Void, String> asyncTask = new TaskWS(StudentsListActivity.this).execute();
try {
Gson gson = new Gson();
ProductList product = gson.fromJson(asyncTask.get(), ProductList.class);
// ArrayAdapter<Product> adapter = new ArrayAdapter<Product>(StudentsListActivity.this, android.R.layout.simple_list_item_1, product.getContent());
productAdapter = new ProductAdapter(product.getContent(), StudentsListActivity.this);
list.setAdapter(productAdapter);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
...
}
public class TaskWS extends AsyncTask<Void, Void, JSONObject> {
Activity mActivity;
public TaskWS(Activity activity) {
super();
this.mActivity = activity;
}
@Override
protected JSONObject doInBackground(Void... params) {
return readProducts();
}
private JSONObject readProducts() {
HttpClientFactory factory = new HttpClientFactory();
JSONObject result = factory.sendGet(Extras.BASE_PRODUCTS);
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment