luongkhanh luongkhanh - 1 month ago 7
Android Question

Can not load data to ListView in Activity

I'm using json to load data in Activity class with content following as:

My Activity class:

public class CategoryCarActivity extends ListActivity {

ConnectionDetector cd;
AlertDialogManager alert = new AlertDialogManager();
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();

ArrayList<Category> carsList = new ArrayList<Category>();
JSONArray manufacturers = null;
String manufacturer_id, manufacturer_name;
private static final String URL_MANUFACTURERS = "MyURL";
// ALL JSON node names
private static final String TAG_CARS = "cars";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_MANUFACTURER = "name";
private static final String TAG_PRICE = "price";

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

cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(CategoryCarActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
Intent i = getIntent();
manufacturer_id = i.getStringExtra("id");

carsList = new ArrayList<Category>();

// Loading tracks in Background Thread
new LoadTracks().execute();

// get listview
ListView lv = getListView();

/**
* Listview on item click listener
* SingleTrackActivity will be lauched by passing manufacturer id, car id
* */
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
// On selecting single track get car information
Intent i = new Intent(getApplicationContext(), DetailListCarActivity.class);
// to get car information
// both manufacturer id and car is needed
String manufacturer_id = ((TextView) view.findViewById(R.id.manufacturer_id)).getText().toString();
String car_id = ((TextView) view.findViewById(R.id.car_id)).getText().toString();

Toast.makeText(getApplicationContext(), "Manufacturer Id: " + manufacturer_id + ", Car Id: " + car_id, Toast.LENGTH_SHORT).show();

i.putExtra("manufacturer_id", manufacturer_id);
i.putExtra("car_id", car_id);

startActivity(i);
}
});

}

/**
* Background Async Task to Load all tracks under one album
* */
class LoadTracks extends AsyncTask<String, String, String> {

/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CategoryCarActivity.this);
pDialog.setMessage("Loading selected car ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}

/**
* getting tracks json and parsing
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();

// post album id as GET parameter
params.add(new BasicNameValuePair(TAG_ID, manufacturer_id));

// getting JSON string from URL
String json = jsonParser.makeHttpRequest(URL_MANUFACTURERS, "GET",
params);

// Check your log cat for JSON reponse
Log.d("Category List JSON: ", json);

try {
JSONObject jObj = new JSONObject(json);
if (jObj != null) {
String manufacturer_id = jObj.getString(TAG_ID);
manufacturer_name = jObj.getString(TAG_MANUFACTURER);
manufacturers = jObj.getJSONArray(TAG_CARS);

if (manufacturers != null) {
// looping through All cars
for (int i = 0; i < manufacturers.length(); i++) {
JSONObject c = manufacturers.getJSONObject(i);

// Storing each json item in variable
String id = c.getString(TAG_ID);
// track no - increment i value
String track_no = String.valueOf(i + 1);
String name = c.getString(TAG_NAME);
String price = c.getString(TAG_PRICE);
// creating new HashMap
// HashMap<String, String> map = new HashMap<String, String>();
Category category = new Category();
category.setManufacturer_id(manufacturer_id);
category.setId(id);
category.setName(name);
category.setPrice(price);

// adding each child node to HashMap key => value
/*
map.put("manufacturer_id", manufacturer_id); // note here
map.put(TAG_ID, car_id);
map.put("track_no", track_no + ".");
map.put(TAG_NAME, name);
map.put(TAG_PRICE, price);
*/
// adding HashList to ArrayList
// carsList.add(map);
carsList.add(category);
}
} else {
Log.d("Manufacturers: ", "null");
}
}

} catch (JSONException e) {
e.printStackTrace();
}

return null;
}

/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String result) {
pDialog.dismiss();

ListAdapter adapter = new ArrayAdapter<Category>(
CategoryCarActivity.this, // the context
R.layout.list_item_categorys, // Simple list item - will toString() your data
carsList // The arraylist
);

// updating listview
setListAdapter(adapter);
}
}
}


list_item_categorys.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >


<TextView
android:id="@+id/manufacturer_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone" />

<!-- Song id / Hidden by default -->
<TextView
android:id="@+id/car_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone" />


<TextView
android:id="@+id/track_no"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="15dip"
android:paddingLeft="5dip"
android:paddingTop="15dip"
android:textColor="#000000"
android:textSize="16dip"
android:layout_alignParentLeft="true"/>

<TextView
android:id="@+id/manufacturer_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="15dip"
android:paddingLeft="5dip"
android:paddingTop="15dip"
android:textColor="#000000"
android:textSize="16dip"
android:layout_toRightOf="@+id/track_no"/>

<TextView
android:id="@+id/price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:paddingLeft="3dip"
android:paddingRight="6dip"
android:textColor="#9ed321" />




I have debugged and check Logcat and see that data has loaded and everything normal, but don't know why data can not load to ListView

updated
Logcat:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.totoroads.android.app, PID: 4697
java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView
at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:393)
at android.widget.ArrayAdapter.getView(ArrayAdapter.java:369)


How to fix this problem?? thank you

Answer

This code looks really similar... maybe copy the rest of it?

You need an Adapter for your data.

protected void onPostExecute(String result) {
    // dismiss the dialog after getting all tracks
    pDialog.dismiss();

    ListAdapter adapter = new ArrayAdapter<Category>(
        CategoryCarActivity.this,     // the context
        android.R.layout.simple_list_item_1, // Simple list item - will toString() your data
        carList                       // The arraylist
    );

    // updating listview
    setListAdapter(adapter);

}

You can also make a subclass of ArrayAdapter<Category> if you really want to customize a layout.

Comments