I am using ViewPager in my app and fetch the data(Images) from server(with JSON). Even if runs smoothly no image is shown in the viewpager.
I read so many tutorial regarding this, but nobody solve my problem. Please tell me where i am wrong...
Here is my code:
view_pager.xml
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="40dp" />
image_view.xml
<ImageView
android:id="#+id/image_adapter"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"/>
ViewPager_Adapter.java
public class ViewPager_Adapter extends PagerAdapter {
private String urls;
private LayoutInflater inflater;
private Context context;
ArrayList<String> mylist;
public ViewPager_Adapter(Context context, ArrayList<String> mylist) {
this.context = context;
this.urls = urls;
this.mylist = mylist;
inflater = LayoutInflater.from(context);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return mylist.size();
}
#Override
public Object instantiateItem(ViewGroup view, int position) {
View imageLayout = inflater.inflate(R.layout.image_view, null);
assert imageLayout != null;
final ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image_adapter);
Glide.with(context)
.load(mylist.get(position))
.into(imageView);
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) {
}
#Override
public Parcelable saveState() {
return null;
}
}
View_Pager.Java
public class View_Pager extends Fragment {
private static ViewPager mPager;
JSONArray responsearray = null;
String imageOne;
private static final String TAG_PHOTO_ONE = "Gallery_Full";
ArrayList<String> myList;
HashMap<String, String> get;
ViewPager_Adapter viewpager_adapter;
LinearLayout addimages;
int REQUEST_CODE = 100;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.view_pager, null);
mPager = view.findViewById(R.id.viewpager);
new GetImages().execute(true);
return view;
}
class GetImages extends AsyncTask<Boolean, Void, String> {
#Override
protected String doInBackground(Boolean... booleans) {
ImageApi imageApi = new ImageApi();
String result = null;
try {
result = imageApi.galleryget(sharedPreferences.getString("id", ""));
JSONObject object = new JSONObject(result);
if (object.getString("error").equalsIgnoreCase("false")) {
responsearray = object.getJSONArray("response");
return "true";
} else {
String errormsg = object.getString(result);
return errormsg;
}
} catch (ApiException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s != null) {
if (s.equalsIgnoreCase("true")) {
showList(responsearray);
}
}
}
}
public void showList(final JSONArray responsearray) {
try {
for (int i = 0; i < responsearray.length(); i++) {
JSONObject responseObject = responsearray.getJSONObject(i);
Log.e("COUNT" + i, String.valueOf(responseObject));
imageOne = responseObject.getString(TAG_PHOTO_ONE);
get = new HashMap<>();
get.put(TAG_PHOTO_ONE, imageOne);
myList = new ArrayList<>();
myList.add(String.valueOf(get));
}
viewpager_adapter = new ViewPager_Adapter(getActivity(), myList);
String test = String.valueOf(myList);
String imgpath = getString(R.string.imgpath);
String finalimgpath = imgpath + imageOne;
Log.e("FINALPATH", finalimgpath);
} catch (JSONException e) {
e.printStackTrace();
}
mPager.setAdapter(viewpager_adapter);
viewpager_adapter.notifyDataSetChanged();
}
}
Use this code for showList() as you are not populating you're arrayList properly the data is being over write in one position .
So , what you have to do is initialize it out side of for loop .
public void showList(final JSONArray responsearray) {
try {
//here
myList = new ArrayList<>();
for (int i = 0; i < responsearray.length(); i++) {
JSONObject responseObject = responsearray.getJSONObject(i);
Log.e("COUNT" + i, String.valueOf(responseObject));
imageOne = responseObject.getString(TAG_PHOTO_ONE);
get = new HashMap<>();
get.put(TAG_PHOTO_ONE, imageOne);
myList.add(String.valueOf(get));
}
viewpager_adapter = new ViewPager_Adapter(getActivity(), myList);
String test = String.valueOf(myList);
String imgpath = getString(R.string.imgpath);
String finalimgpath = imgpath + imageOne;
Log.e("FINALPATH", finalimgpath);
} catch (JSONException e) {
e.printStackTrace();
}
mPager.setAdapter(viewpager_adapter);
viewpager_adapter.notifyDataSetChanged();
}
Edit
Also if your final image path is as below then you have to update your code in adapter for image path as follow.
Update position in view.addView() too.
String test = String.valueOf(mylist.get(position));
String imgpath = getString(R.string.imgpath);
String finalimgpath = imgpath + test;
Glide.with(context)
.load(finalimgpath)
.into(imageView);
view.addView(imageLayout,position);
return imageLayout;
In your For loop you are initialising your list everytime
for (int i = 0; i < responsearray.length(); i++) {
JSONObject responseObject = responsearray.getJSONObject(i);
Log.e("COUNT" + i, String.valueOf(responseObject));
imageOne = responseObject.getString(TAG_PHOTO_ONE);
get = new HashMap<>();
get.put(TAG_PHOTO_ONE, imageOne);
myList = new ArrayList<>(); // THIS IS WRONG. don't initialise every time
myList.add(String.valueOf(get)); // THIS IS ALSO WRONG. you are adding hashmap object to list
}
So make your for loop like this
myList = new ArrayList<>();
for (int i = 0; i < responsearray.length(); i++) {
JSONObject responseObject = responsearray.getJSONObject(i);
Log.e("COUNT" + i, String.valueOf(responseObject));
imageOne = responseObject.getString(TAG_PHOTO_ONE);
get = new HashMap<>();
get.put(TAG_PHOTO_ONE, imageOne);
myList.add(imageOne);
}
I'm getting json data and putting it in hashmap and hashmap into an arraylist. All is happening in fragment extending ListFragment
protected String doInBackground(String... urls) {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("full_name", etUserSearch.getText().toString());
responseReceive = JsonPostClient.SendHttpPost(urls[0],
jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
try {
Success = responseReceive.getJSONArray("Success");
for (int i = 0; i < Success.length(); i++) {
JSONObject c = Success.getJSONObject(i);
String full_name = c.getString(TAG_FULL_NAME);
String user_name = c.getString(TAG_USER_NAME);
String user_id = c.getString(TAG_USER_ID);
HashMap<String, String> friends = new HashMap<String, String>();
// adding each child node to HashMap key => value
friends.put(TAG_FULL_NAME, full_name);
friends.put(TAG_USER_NAME, user_name);
friends.put(TAG_USER_ID, user_id);
// adding contact to contact list
FriendSearchList.add(friends);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.d("hello", "");
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
printFriends();
};
I'm checking that data is valid by printFriends() method and wanna show only 'TAG_FULL_NAME' data in a listview. My ListView initialization
View rootView = inflater.inflate(R.layout.tab_add_friends, container,
false);
lv = (ListView) rootView.findViewById(R.id.listView);
Method for checking data and loading in ListView
public void printFriends() {
int len = FriendSearchList.size();
for (int i = 0; i < len; i++) {
String f_name = FriendSearchList.get(i).get(TAG_FULL_NAME);
String u_name = FriendSearchList.get(i).get(TAG_USER_NAME);
String u_id = FriendSearchList.get(i).get(TAG_USER_ID);
Log.d("full_name", f_name);
Log.d("user_name", u_name);
Log.d("user_id", u_id);
}
ListAdapter adapter = new SimpleAdapter(getActivity(),
FriendSearchList, R.layout.tab_addfriend_list,
new String[] { TAG_FULL_NAME }, new int[] { R.id.full_name });
setListAdapter(adapter);
}
tab_add_friends xml layout
<?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" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
tab_addfriend_list xml 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="wrap_content"
android:orientation="vertical"
android:padding="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" >
<!-- Name Label -->
<TextView
android:id="#+id/full_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:textColor="#43bd00"
android:textSize="16sp"
android:textStyle="bold" />
</LinearLayout>
There is no error showing just nothing is showing into listview. Need suggestion or clue to get rid of this problem.
I have the same problem once
the problem is you are feeding the data using simple adapter but you may be inflate the rowView outside the ui thread and feed the from the post execute . thtas why your view dont getting the data . actually you dont have to inflate the rowview here is the hole code for you .Another thing print friend method also useless just initialize the simple adapter in the onPostExecute() method.
`public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://api.androidhive.info/contacts/";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
private boolean isConnection = false;
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
ArrayList<HashMap<String, String>> oflineContactList;
private MyContactDataSource dataSource;
List<Contatcs> oflineContatcs;
// private ListAdapter adapter1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataSource = new MyContactDataSource(MainActivity.this);
dataSource.open();
contactList = new ArrayList<HashMap<String,String>>();
oflineContactList = dataSource.getContatcs();
Log.i("data", oflineContactList.toString());
ListView lv = getListView();
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, oflineContactList,
R.layout.list_item, new String[] { TAG_NAME, TAG_EMAIL,
TAG_PHONE_MOBILE }, new int[] { R.id.email,
R.id.name, R.id.mobile });
setListAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// getting values from selected ListItem
String name = ((TextView) arg1.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) arg1.findViewById(R.id.email))
.getText().toString();
String description = ((TextView) arg1.findViewById(R.id.mobile))
.getText().toString();
// Starting single contact activity
Intent intent = new Intent(MainActivity.this, SingleListItemActivity.class);
intent.putExtra(TAG_NAME, name);
intent.putExtra(TAG_EMAIL, cost);
intent.putExtra(TAG_PHONE_MOBILE, description);
startActivity(intent);
}
});
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Data is loading...please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Creating service handler class instance
ServiceHandler mHandler = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = mHandler.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if(jsonStr != null){
try {
JSONObject jsonObject = new JSONObject(jsonStr);
//Getting JSON Array node
contacts = jsonObject.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone node is JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_EMAIL, email);
contact.put(TAG_PHONE_MOBILE, mobile);
// adding contact to contact list
contactList.add(contact);
}
dataSource.creareContacts(contactList);
dataSource.close();
} catch (JSONException e) {
e.printStackTrace();
}
}
else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if(pDialog.isShowing()){
pDialog.dismiss();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[] { TAG_NAME, TAG_EMAIL,
TAG_PHONE_MOBILE }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}
}`
The problem is that you are passing an Arraylist of HashMap where SimpleAdapter wont have any idea on which data is to put in the layout of the ListView items.
You can use this to implement items in your ListView
sample:
ListAdapter adapter = new SimpleAdapter(getActivity(),
FriendSearchList, R.layout.tab_addfriend_list,
new String[] { TAG_FULL_NAME }, new int[] { R.id.full_name }){
#Override
public int getCount() {
return FriendSearchList.size();
}
#Override
public View getView(int position,View convertView,ViewGroup parent) {
View v;
if(convertView == null)
{
v = getActivity().getLayoutInflater().inflate(R.layout.tab_addfriend_list, parent);
TextView tx = (TextView) v.findViewById(R.id.full_name);
tx.setText(FriendSearchList.get(i).get(TAG_FULL_NAME));
} else
v = convertView;
return v;
}
};
I have the following code which retrieves the JSON file:
public class GetJSON extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) { //Running in background
try {
httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://pagesbyz.com/test.json");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
Log.i("TEST", e.toString());
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return null;
}
#Override
protected void onPreExecute() { //Activity is on progress
}
#Override
protected void onPostExecute(Void v) { //Activity is done...
Toast.makeText(getActivity(), result, 2000).show();
int k = 0;
try {
JSONArray jsonall = new JSONArray();
jsonArray = new JSONArray(result);
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = (JSONObject)jsonArray.get(i); // get the json object
if(jsonObj.getString("type").equals("image") || jsonObj.getString("type").equals("text")) { // compare for the key-value
k++;
jsonall.put(jsonObj);
sId = new String[jsonall.length()];
sType = new String[jsonall.length()];
sData = new String[jsonall.length()];
for (int m = 0 ; m < jsonall.length(); m++){ //4 entries made
JSONObject c = jsonall.getJSONObject(m);
String id = c.getString("id");
String type = c.getString("type");
String data = c.getString("data");
sId[m] = id;
sType[m] = type;
sData[m] = data;
}
}
}
Toast.makeText(getActivity(), String.valueOf(k), 2000).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
On the onPostExecute() function I am able to de-serialize the data, in this case by TYPE.
I have the following code for the CustomAdapter
public class SetRowsCustomAdapter extends ArrayAdapter<SetRows> {
Context context;
int layoutResourceId;
ArrayList<SetRows> data=new ArrayList<SetRows>();
public SetRowsCustomAdapter(Context context, int layoutResourceId, ArrayList<SetRows> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ImageHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ImageHolder();
holder.tID = (TextView)row.findViewById(R.id.tvID);
holder.tType = (TextView)row.findViewById(R.id.tvType);
holder.tData = (TextView)row.findViewById(R.id.tvData);
row.setTag(holder);
}
else
{
holder = (ImageHolder)row.getTag();
}
SetRows myImage = data.get(position);
holder.tID.setText(myImage.id);
holder.tType.setText(myImage.type);
holder.tData.setText(myImage.data);
return row;
}
static class ImageHolder
{
TextView tID;
TextView tType;
TextView tData;
}
}
My SetRows code is:
public class SetRows {
String id;
String type;
String data;
public String getData () {
return data;
}
public void setData (String data) {
this.data = data;
}
public String getID () {
return id;
}
public void setID (String id) {
this.id = id;
}
public String getType () {
return type;
}
public void setType (String type) {
this.type = type;
}
public SetRows(String id, String type, String data) {
super();
this.id = "ID: \t" + id;
this.type = "TYPE: \t" + type;
this.data = "DATA: \t" + data;
}
}
My XML file for the Layout file is:
<?xml version="1.0" encoding="utf-8"?>
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ListView android:id="#+id/lvAll"
android:layout_height="match_parent"
android:layout_width="match_parent" />
</RelativeLayout>
The custom layout for the ListView is:
<?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="#dimen/list_row_pad"
android:background="#drawable/list_row_bg" >
<TextView
android:id="#+id/tvID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="#dimen/margin_left_tv"
android:text="ID: "
android:textStyle="bold"
android:textColor="#FFFFFF" />
<TextView
android:id="#+id/tvType"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvID"
android:layout_alignLeft="#+id/tvID"
android:text="TYPE: "
android:textStyle="bold"
android:textColor="#FFFFFF" />
<TextView
android:id="#+id/tvData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvType"
android:layout_alignLeft="#+id/tvType"
android:text="DATA: "
android:textStyle="bold"
android:textColor="#FFFFFF" />
</RelativeLayout>
I want to display the data like this in a ListView from the JSON file from my server:
I think I have all the information needed. I just need to know, now, how to display the information. All help is greatly appreciated. Thanks!
UPDATE: The following code is working, but it's entering multiple entries for each:
public class GetJSON extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) { //Running in background
try {
httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://pagesbyz.com/test.json");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
Log.i("TEST", e.toString());
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return null;
}
#Override
protected void onPreExecute() { //Activity is on progress
}
#Override
protected void onPostExecute(Void v) { //Activity is done...
//Toast.makeText(getActivity(), result, 2000).show();
int k = 0;
try {
JSONArray jsonall = new JSONArray();
jsonArray = new JSONArray(result);
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = (JSONObject)jsonArray.get(i); // get the json object
if(jsonObj.getString("type").equals("image") || jsonObj.getString("type").equals("text")) { // compare for the key-value
k++;
jsonall.put(jsonObj);
sId = new String[jsonall.length()];
sType = new String[jsonall.length()];
sData = new String[jsonall.length()];
for (int m = 0 ; m < jsonall.length(); m++){
JSONObject c = jsonall.getJSONObject(m);
String id = c.getString("id");
String type = c.getString("type");
String data = c.getString("data");
//sId[m] = id;
//sType[m] = type;
//sData[m] = data;
contents.add(new SetRows(id, type, data));
}
}
adapter = new SetRowsCustomAdapter(getActivity(), R.layout.listrow, contents);
lAll.setAdapter(adapter);
lAll.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent myIntent = new Intent(getActivity(), DisplayWeb.class);
startActivityForResult(myIntent, 0);
}
});
}
//Toast.makeText(getActivity(), String.valueOf(k), 2000).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
The duplicate shows up as like this:
Sublacss ListActivy and create a layout that contains a ListView with id #android:id/list
put inside this subclass you AsyncTask and execute it in the on create.
when onPostExecute is called, after you parse the JSON, create an instance of SetRowsCustomAdapter
call getListView().setAdapter(adapterInstance).
#Override
protected void onPostExecute(Void v) {
ArrayList<SetRows> contents = new ArrayList<SetRows>();
// other code
//instead of those
//sId[m] = id;
//sType[m] = type;
//sData[m] = data;
//add
contents.add(new SetRows(id, type, data));
}
Edit 2: You have two duplicates entry because you have an unuseful for loop (the innere one). Imo your code should look like:
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = (JSONObject)jsonArray.get(i);
if(jsonObj.getString("type").equals("image") || jsonObj.getString("type").equals("text")) {
String id = jsonObj.getString("id");
String type = jsonObj.getString("type");
String data = jsonObj.getString("data");
contents.add(new SetRows(id, type, data));
}
}
// the other stuff
ps. check for typo
A large part of my app is grabbing data from a website. The data shows in my logcat, green with no errors but will not display in my android view. Ive tried and searched for a week or and have had no luck.
here is my class.
public class Json extends ListActivity {
ArrayList<HashMap<String, String>> jsonParser = new ArrayList<HashMap<String, String>>();
ListView lv ;
private static final String jsonFilePath = "http://xda.olinksoftware.com/leaderboard/all";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.json);
new ProgressTask(Json.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
public ProgressTask(Json json) {
Log.i("1", "Called");
context = json;
dialog = new ProgressDialog(context);
}
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
ListAdapter adapter = new SimpleAdapter(context, jsonParser,
R.layout.listitem, new String[] { TAG_NAME, TAG_SCORE,
}, new int[] {
R.id.score, R.id.name,
});
setListAdapter(adapter);
// selecting single ListView item
lv = getListView();
}
#Override
protected Boolean doInBackground(final String... args) {
new JSONParser();
try {
BufferedReader reader = null;
String jsonString = "";
StringBuffer buffer = new StringBuffer();
try{
URL url = new URL(jsonFilePath);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
}finally {
if (reader != null)
reader.close();
}
jsonString = buffer.toString();
try{
JSONParser jsonParser = new JSONParser();
JSONArray leaderboard = (JSONArray)jsonParser.parse(jsonString);
for(int i = 0;i<leaderboard.size();i++){
JSONObject user = (JSONObject)leaderboard.get(i);
System.out.println((i+1) + ". " + user.get("forumName") + " (" + user.get("score") + ")");
}
}catch(ParseException pe){
System.out.println("position: " + pe.getPosition());
System.out.println(pe);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}}
}
and here are my xml.
<?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">
<!-- Main ListView
Always give id value as list(#android:id/list)
-->
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
<?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="wrap_content"
android:orientation="vertical">
<!-- Product id (pid) - will be HIDDEN - used to pass to other activity -->
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<!-- Name Label -->
<TextView
android:id="#+id/score"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="6dp"
android:paddingLeft="6dp"
android:textSize="17sp"
android:textStyle="bold"/>
</LinearLayout>
any help is greatly appreciated. I know I am doing something wrong with my listview as it also works as a straight java application run in eclipse.
here is the data i am grabbing, i am only taking two values at this time. "forumUser" and "score"
[{"userId":"3579348","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=3579348","forumName":"newtoroot","totalPosts":"5074","postsPerDay":"5.14","totalThanks":"18302","joinDate":"2011-01-29","yearsJoined":"2","referrals":"4","friendCount":"38","recognizedDeveloper":"1","recognizedContributor":"0","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"48","kernelCount":"0","tutorialCount":"0","modCount":"1","themeCount":"0","score":"302","userName":"","password":""},{"userId":"1596076","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=1596076","forumName":"il Duce","totalPosts":"16335","postsPerDay":"9.75","totalThanks":"15799","joinDate":"2009-02-25","yearsJoined":"4","referrals":"2","friendCount":"83","recognizedDeveloper":"1","recognizedContributor":"0","recognizedThemer":"0","moderator":"1","recognizedEliteDeveloper":"0","romCount":"1","kernelCount":"1","tutorialCount":"0","modCount":"0","themeCount":"0","score":"132","userName":"","password":""},{"userId":"2930301","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=2930301","forumName":"fernando sor","totalPosts":"8967","postsPerDay":"7.93","totalThanks":"4549","joinDate":"2010-09-07","yearsJoined":"3","referrals":"2","friendCount":"29","recognizedDeveloper":"0","recognizedContributor":"0","recognizedThemer":"1","moderator":"0","recognizedEliteDeveloper":"0","romCount":"1","kernelCount":"0","tutorialCount":"5","modCount":"2","themeCount":"15","score":"120","userName":"fernando sor","password":""},{"userId":"3220669","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=3220669","forumName":"1975jamie","totalPosts":"582","postsPerDay":"0.56","totalThanks":"127","joinDate":"2010-11-23","yearsJoined":"2","referrals":"0","friendCount":"0","recognizedDeveloper":"1","recognizedContributor":"0","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"4","kernelCount":"0","tutorialCount":"0","modCount":"0","themeCount":"0","score":"46","userName":"1975jamie","password":""},{"userId":"2552854","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=2552854","forumName":"jeffsanace","totalPosts":"2797","postsPerDay":"2.25","totalThanks":"2836","joinDate":"2010-05-05","yearsJoined":"3","referrals":"0","friendCount":"12","recognizedDeveloper":"0","recognizedContributor":"1","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"0","kernelCount":"0","tutorialCount":"0","modCount":"0","themeCount":"0","score":"37","userName":"","password":""},{"userId":"2067958","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=2067958","forumName":"eg1122","totalPosts":"1200","postsPerDay":"0.82","totalThanks":"1695","joinDate":"2009-10-05","yearsJoined":"3","referrals":"0","friendCount":"6","recognizedDeveloper":"0","recognizedContributor":"0","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"0","kernelCount":"0","tutorialCount":"0","modCount":"2","themeCount":"0","score":"20","userName":"","password":""},{"userId":"3042344","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=3042344","forumName":"dfuse06","totalPosts":"3331","postsPerDay":"3.08","totalThanks":"2270","joinDate":"2010-10-11","yearsJoined":"2","referrals":"1","friendCount":"29","recognizedDeveloper":"0","recognizedContributor":"0","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"0","kernelCount":"0","tutorialCount":"0","modCount":"1","themeCount":"0","score":"17","userName":"","password":""},{"userId":"1070340","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=1070340","forumName":"chrisloveskaos","totalPosts":"215","postsPerDay":"0.11","totalThanks":"8","joinDate":"2008-07-08","yearsJoined":"5","referrals":"0","friendCount":"7","recognizedDeveloper":"0","recognizedContributor":"0","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"1","kernelCount":"0","tutorialCount":"0","modCount":"0","themeCount":"0","score":"14","userName":"","password":""},{"userId":"2688514","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=2688514","forumName":"GooTz66","totalPosts":"999","postsPerDay":"0.84","totalThanks":"70","joinDate":"2010-06-25","yearsJoined":"3","referrals":"0","friendCount":"7","recognizedDeveloper":"0","recognizedContributor":"0","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"0","kernelCount":"0","tutorialCount":"0","modCount":"0","themeCount":"0","score":"7","userName":"","password":""},{"userId":"2141845","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=2141845","forumName":"Kush.Kush\u00c2\u0099","totalPosts":"86","postsPerDay":"0.06","totalThanks":"0","joinDate":"2009-11-09","yearsJoined":"3","referrals":"0","friendCount":"16","recognizedDeveloper":"0","recognizedContributor":"0","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"0","kernelCount":"0","tutorialCount":"0","modCount":"0","themeCount":"0","score":"6","userName":"","password":""}]
Why is this line
setListAdapter(adapter);
Before this
// selecting single ListView item
lv = getListView();
Also, the LogCat you posted is showing the results using the "info" filter only. Try looking at the verbose view to make sure no exceptions that you're missing.
what i did to solve this was pretty much start over. i added a JSONParser class
public class JSONParser {
static InputStream is = null;
static JSONArray jarray = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e("==>", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// try parse the string to a JSON object
try {
jarray = new JSONArray( builder.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jarray;
and a JsonActivity
public class MainActivity extends ListActivity {
private static String url = "website";
private static final String TAG_VTYPE = "forumName";
private static final String TAG_VCOLOR = "score";
private static final String TAG_THANKS = "totalThanks";
private static final String TAG_POSTS = "totalPosts";
private static final String TAG_JOIN_DATE = "joinDate";
private static final String TAG_ROM_COUNT = "romCount";
private static final String TAG_THEME_COUNT = "themeCount";
private static final String TAG_MOD_COUNT = "modCount";
private static final String TAG_KERNEL_COUNT = "kernelCount";
private static final String TAG_TUTORIAL_COUNT = "tutorialCount";
private static final String TAG_DEV = "recognizedDeveloper";
private static final String TAG_THEMER = "recognizedThemer";
private static final String TAG_MODERATOR = "moderator";
private static final String TAG_RDEV = "recognizedEliteDeveloper";
private static final String TAG_RCOD = "recognizedContributor";
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
private View header;
ListView lv ;
LayoutInflater Inflater;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_view);
Inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
new ProgressTask(MainActivity.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
private ListActivity activity;
// private List<Message> messages;
public ProgressTask(ListActivity activity) {
this.activity = activity;
context = activity;
dialog = new ProgressDialog(context);
}
/** progress dialog to show user that the backup is processing. */
/** application context. */
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
View header = Inflater.inflate(R.layout.header_view_name, null);
ListAdapter adapter = new SimpleAdapter(context, jsonlist,
R.layout.list_item, new String[] { TAG_VTYPE, TAG_VCOLOR, TAG_THANKS, TAG_POSTS, TAG_JOIN_DATE, TAG_ROM_COUNT,
TAG_THEME_COUNT, TAG_MOD_COUNT, TAG_KERNEL_COUNT, TAG_DEV, TAG_TUTORIAL_COUNT, TAG_THEMER, TAG_MODERATOR, TAG_RDEV, TAG_RCOD,
}, new int[] {
R.id.vehicleType, R.id.vehicleColor, R.id.totalThanks, R.id.totalPosts, R.id.joinDate, R.id.romCount,
R.id.themeCount, R.id.kernelCount, R.id.modCount, R.id.tutorialCount, R.id.moderator, R.id.rThemer, R.id.rDev,
R.id.rCon, R.id.rEliteDev,
});
lv = getListView();
lv.addHeaderView(header);
setListAdapter(adapter);
// selecting single ListView item
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
;
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// getting values from selected ListItem
String forumName = ((TextView) view.findViewById(R.id.vehicleType)).getText().toString();
String score = ((TextView) view.findViewById(R.id.vehicleColor)).getText().toString();
String totalThanks = ((TextView) view.findViewById(R.id.totalThanks)).getText().toString();
String totalPosts = ((TextView) view.findViewById(R.id.totalPosts)).getText().toString();
String joinDate = ((TextView) view.findViewById(R.id.joinDate)).getText().toString();
String romCount = ((TextView) view.findViewById(R.id.romCount)).getText().toString();
String themeCount = ((TextView) view.findViewById(R.id.themeCount)).getText().toString();
String kernelCount = ((TextView) view.findViewById(R.id.kernelCount)).getText().toString();
String modCount = ((TextView) view.findViewById(R.id.modCount)).getText().toString();
String tutorialCount = ((TextView) view.findViewById(R.id.tutorialCount)).getText().toString();
String moderator = ((TextView) view.findViewById(R.id.moderator)).getText().toString();
String recognizedThemer = ((TextView) view.findViewById(R.id.rThemer)).getText().toString();
String recognizedDeveloper = ((TextView) view.findViewById(R.id.rDev)).getText().toString();
String recognizedContributor = ((TextView) view.findViewById(R.id.rCon)).getText().toString();
String recognizedEliteDeveloper = ((TextView) view.findViewById(R.id.rEliteDev)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_VTYPE, forumName);
in.putExtra(TAG_VCOLOR, score);
in.putExtra(TAG_THANKS, totalThanks);
in.putExtra(TAG_POSTS, totalPosts);
in.putExtra(TAG_JOIN_DATE, joinDate);
in.putExtra(TAG_ROM_COUNT, romCount);
in.putExtra(TAG_THEME_COUNT, themeCount);
in.putExtra(TAG_MOD_COUNT, modCount);
in.putExtra(TAG_KERNEL_COUNT, kernelCount);
in.putExtra(TAG_TUTORIAL_COUNT, tutorialCount);
in.putExtra(TAG_DEV, recognizedDeveloper);
in.putExtra(TAG_THEMER, recognizedThemer);
in.putExtra(TAG_MODERATOR, moderator);
in.putExtra(TAG_RDEV, recognizedEliteDeveloper);
in.putExtra(TAG_RCOD, recognizedContributor);
startActivity(in);
}});}
protected Boolean doInBackground(final String... args) {
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url);
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String forumName = c.getString(TAG_VTYPE);
String score = c.getString(TAG_VCOLOR);
String totalThanks = c.getString(TAG_THANKS);
String totalPosts = c.getString(TAG_POSTS);
String joinDate = c.getString(TAG_JOIN_DATE);
String romCount = c.getString(TAG_ROM_COUNT);
String themeCount = c.getString(TAG_THEME_COUNT);
String modCount = c.getString(TAG_MOD_COUNT);
String kernelCount = c.getString(TAG_KERNEL_COUNT);
String tutorialCount = c.getString(TAG_TUTORIAL_COUNT);
String recognizedDeveloper = c.getString(TAG_DEV);
String recognizedThemer = c.getString(TAG_THEMER);
String moderator = c.getString(TAG_MODERATOR);
String recognizedEliteDeveloper = c.getString(TAG_RDEV);
String recognizedContributor = c.getString(TAG_RCOD);
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_VTYPE, forumName);
map.put(TAG_VCOLOR, score);
map.put(TAG_THANKS, totalThanks);
map.put(TAG_POSTS, totalPosts);
map.put(TAG_JOIN_DATE, joinDate);
map.put(TAG_ROM_COUNT, romCount);
map.put(TAG_THEME_COUNT, themeCount);
map.put(TAG_MOD_COUNT, modCount);
map.put(TAG_KERNEL_COUNT, kernelCount);
map.put(TAG_TUTORIAL_COUNT, tutorialCount);
map.put(TAG_DEV, recognizedDeveloper);
map.put(TAG_THEMER, recognizedThemer);
map.put(TAG_MODERATOR, moderator);
map.put(TAG_RDEV, recognizedEliteDeveloper);
map.put(TAG_RCOD, recognizedContributor);
jsonlist.add(map);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}}}
and tied it together with a list view and xml for all my values. turned out really cool. i added an onclick on each value to show more individual data