Reputation:
I'm still pretty new to Android development, am doing an app/project which involves loading this JSON (listed below) into a ListView
with the name, description, and image, but it has been coming up blank on the emulator. Please tell me what I'm doing wrong - any help would be greatly appreciated! (The more specific the better as I am such a newbie..)
JSON:
{
"success":true,
"games":[
{
"id":"1",
"name":"Name of the Game",
"description":"This is what it is about",
"image":"IMAGE URL"
}
]
}
AndroidJSONParsingActivity:
// URL to make request
private static final String url = "URL of API";
// JSON Node names
private static final String TAG_GAMES = "games";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_IMAGE = "image";
// games JSONArray
JSONArray games = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hash map for ListView
ArrayList<HashMap<String, String>> gameList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Games
games = json.getJSONArray(TAG_GAMES);
// looping through All Games
for(int i = 0; i < games.length(); i++){
JSONObject c = games.getJSONObject(i);
// Storing each JSON item in variable
String id = c.getString(TAG_ID);
String image = c.getString(TAG_IMAGE);
// is again JSON Object
JSONObject author = c.getJSONObject(TAG_DESCRIPTION);
String name = author.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put( TAG_IMAGE, image);
// adding HashList to ArrayList
gameList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, gameList,
R.layout.list_item,
new String[] { TAG_NAME, TAG_DESCRIPTION }, new int[] {
R.id.name, R.id.description });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String description = ((TextView) view.findViewById(R.id.description)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_DESCRIPTION, description);
startActivity(in);
}
});
}
JSON Parser:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
main.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>
list_item.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="wrap_content"
android:orientation="vertical">
<!-- Name Label -->
<TextView
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#43bd00"
android:textSize="16sp"
android:textStyle="bold"
android:paddingTop="6dip"
android:paddingBottom="2dip" />
<TextView
android:id="@+id/description"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#acacac"
android:paddingBottom="2dip" />
</LinearLayout>
Adding LogCat info:
01-03 06:16:15.254: E/ActivityThread(616): Service com.android.exchange.ExchangeService has leaked ServiceConnection com.android.emailcommon.service.ServiceProxy$ProxyConnection@40d47b40 that was originally bound here
01-03 06:16:15.254: E/ActivityThread(616): android.app.ServiceConnectionLeaked: Service com.android.exchange.ExchangeService has leaked ServiceConnection com.android.emailcommon.service.ServiceProxy$ProxyConnection@40d47b40 that was originally bound here
01-03 06:16:15.254: E/ActivityThread(616): at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:969)
01-03 06:16:15.254: E/ActivityThread(616): at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:863)
01-03 06:16:15.254: E/ActivityThread(616): at android.app.ContextImpl.bindService(ContextImpl.java:1418)
01-03 06:16:15.254: E/ActivityThread(616): at android.app.ContextImpl.bindService(ContextImpl.java:1407)
01-03 06:16:15.254: E/ActivityThread(616): at android.content.ContextWrapper.bindService(ContextWrapper.java:473)
01-03 06:16:15.254: E/ActivityThread(616): at com.android.emailcommon.service.ServiceProxy.setTask(ServiceProxy.java:157)
01-03 06:16:15.254: E/ActivityThread(616): at com.android.emailcommon.service.ServiceProxy.setTask(ServiceProxy.java:145)
01-03 06:16:15.254: E/ActivityThread(616): at com.android.emailcommon.service.ServiceProxy.test(ServiceProxy.java:191)
01-03 06:16:15.254: E/ActivityThread(616): at com.android.exchange.ExchangeService$7.run(ExchangeService.java:1850)
01-03 06:16:15.254: E/ActivityThread(616): at com.android.emailcommon.utility.Utility$2.doInBackground(Utility.java:551)
01-03 06:16:15.254: E/ActivityThread(616): at com.android.emailcommon.utility.Utility$2.doInBackground(Utility.java:549)
01-03 06:16:15.254: E/ActivityThread(616): at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-03 06:16:15.254: E/ActivityThread(616): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
01-03 06:16:15.254: E/ActivityThread(616): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
01-03 06:16:15.254: E/ActivityThread(616): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
01-03 06:16:15.254: E/ActivityThread(616): at java.lang.Thread.run(Thread.java:856)
01-03 06:16:15.365: E/StrictMode(616): null
01-03 06:16:15.365: E/StrictMode(616): android.app.ServiceConnectionLeaked: Service com.android.exchange.ExchangeService has leaked ServiceConnection com.android.emailcommon.service.ServiceProxy$ProxyConnection@40d47b40 that was originally bound here
01-03 06:16:15.365: E/StrictMode(616): at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:969)
01-03 06:16:15.365: E/StrictMode(616): at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:863)
01-03 06:16:15.365: E/StrictMode(616): at android.app.ContextImpl.bindService(ContextImpl.java:1418)
01-03 06:16:15.365: E/StrictMode(616): at android.app.ContextImpl.bindService(ContextImpl.java:1407)
01-03 06:16:15.365: E/StrictMode(616): at android.content.ContextWrapper.bindService(ContextWrapper.java:473)
01-03 06:16:15.365: E/StrictMode(616): at com.android.emailcommon.service.ServiceProxy.setTask(ServiceProxy.java:157)
01-03 06:16:15.365: E/StrictMode(616): at com.android.emailcommon.service.ServiceProxy.setTask(ServiceProxy.java:145)
01-03 06:16:15.365: E/StrictMode(616): at com.android.emailcommon.service.ServiceProxy.test(ServiceProxy.java:191)
01-03 06:16:15.365: E/StrictMode(616): at com.android.exchange.ExchangeService$7.run(ExchangeService.java:1850)
01-03 06:16:15.365: E/StrictMode(616): at com.android.emailcommon.utility.Utility$2.doInBackground(Utility.java:551)
01-03 06:16:15.365: E/StrictMode(616): at com.android.emailcommon.utility.Utility$2.doInBackground(Utility.java:549)
01-03 06:16:15.365: E/StrictMode(616): at android.os.AsyncTask$2.call(AsyncTask.java:287)
Upvotes: 2
Views: 1144
Reputation: 1026
AsyncTask.class
class LoadMovies extends AsyncTask<Void, Void, List<Category>>{
private YourActivity activity;
public LoadMovies(YourActivity activty){
activity = activty;
}
private final static String TAG = "Log";
@Override
protected List<Category> doInBackground(Void... params) {
InputStream ips = null;
JSONObject json = null;
try{
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(new HttpGet("http://youtsite"));
ips = response.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(ips));
StringBuilder builder = new StringBuilder();
String line;
while((line = buffer.readLine()) != null){
builder.append(line+"\n");
}
json = new JSONObject(builder.toString());
}
catch(Exception e){
Log.i(TAG, e.toString());
}
List<Category> list = new ArrayList<Category>();
JSONArray array = json.optJSONObject("data").optJSONArray("reviews");
for (int i = 0; i < array.length(); i++){
JSONObject rss = array.optJSONObject(i);
Category cat = new Category();
cat.addName(rss.optString("name"));
cat.addCode(rss.optString("code"));
list.add(cat);
}
return list;
}
protected void onPostExecute(List<Category> result){
super.onPostExecute(result);
Youractivity.mMoviesAdapter.addCategory(result);
}
}
Category.class
public class Category {
private String name;
private String code;
void addName(String name){
this.name = name;
}
void addCode(String code){
this.code = code;
}
public String getName(){
return this.name;
}
String getCode(){
return this.code;
}
}
Adapter.class
class MoviesAdapter extends ArrayAdapter<Category> {
Context c;
List<Category> mListCategory;
public MoviesAdapter(Context context, int resource, int textViewResource, List<Categoryy> list) {
super(context, resource, textViewResource, list);
c = context;
mListCategory= list;
}
public void addCategory(List<MoviesCategory> list){
mListCategory.addAll(list);
notifyDataSetChanged();
}
@Override
public View getView(int position, View convertView, ViewGroup parent){
View v = convertView;
if(v == null){
LayoutInflater inflater = LayoutInflater.from(c);
v = inflater.inflate(R.layout.yourview, null);
}
TextView title = (TextView) v.findViewById(R.id.title);
TextView code= (TextView) v.findViewById(R.id.code);
Category cat = getItem(position);
if(mov != null){
title.setText(cat.getName());
code.setText(cat.getCode());
}
return v;
}
}
And in MainActivity call all
public class YourActivity extends MainActivity{
private ListView mCategory;
private List<Category> mCategoryArray = new ArrayList<Category>();
private LoadMovies mLoadMovies;
public mMoviesAdapter adapter;
@Override
protected void onCreate(Bundle bundle){
super.onCreate(bundle);
//MoviesList
mMoviesAdapter = new MoviesAdapter(this, R.layout.main_movies_adapter, R.id.youradapterlayout, mCategoryArray );
mCategoryList = (ListView) findViewById(R.id.movies_adapter_list);
mMoviesList.setAdapter(mMoviesAdapter);
mLoadMovies = new LoadMovies(this);
mLoadMovies.execute();
}
}
Upvotes: 1
Reputation: 1534
this is my code
public class as extends AsyncTask {
public as(int aa) {
}
@Override protected Object doInBackground(Object... params) { //int price1,sp1,save1; try { JSONObject json = JSONfunctions.getJSONfromURL("http://192.168.1.97/inventory/Client.php?action=productlist&page_no="+aa+"&user_id="+userid+""); Log.e("url", String.valueOf("http://192.168.1.97/inventory/Client.php?action=productlist&page_no="+aa+"&user_id="+userid+"")); mylist = new ArrayList<HashMap<String, String>>();
try{
JSONArray products = json.getJSONArray("product");
Log.v("inside", "inside");
Log.e("pages",String.valueOf( json.get("products_count")));
pagecount=json.getInt("page_count");
//JSONObject e1 = pages.getJSONObject("tot_pages");
// Log.e("totpages",e1.getString("tot_pages"));
// pagecount=json.getInt("tot_pages");
// pcount=json.getInt("p_count");
for(int i=0;i<products.length();i++){
String img,img1;
HashMap<String, String> map = new HashMap<String, String>();
Log.e("p c",String.valueOf(i));
JSONObject e = products.getJSONObject(i);
Log.v("name", String.valueOf(e.getString("name")));
map.put("name",e.getString("name"));
map.put("price",e.getString("price"));
map.put("sp",e.getString("special_price"));
map.put("image", String.valueOf(e.getString("image")));
float price1 = Float.parseFloat(e.getString("price"));
float sp1=Float.parseFloat(e.getString("special_price"));
float save1=price1-sp1;
map.put("save",String.valueOf(save1));
mylist.add(map);
}
}catch(JSONException e)
{
Log.e("log_tag", "Error parsing data "+e.toString());
}
} catch(Exception e)
{ e.printStackTrace();
}
return null;
}
@Override protected void onPostExecute(Object result) { //lv.setAdapter(new ItemListBaseAdapter(AllItems.this, mylist));
}
@Override protected void onPreExecute() { try{ progressDialog = ProgressDialog.show(AllItems.this, "", "Please wait"); } catch (Exception e) {
e.printStackTrace();
} super.onPreExecute(); }
} //previous check method
public class ItemListBaseAdapter extends BaseAdapter {
private ArrayList<HashMap<String, String>> itemDetailsrrayList; Bitmap bitmap[]; Context context1; String ab;
private LayoutInflater l_Inflater;
public ItemListBaseAdapter(Context context, ArrayList<HashMap<String, String>> mylist) {
itemDetailsrrayList = mylist; //l_Inflater = LayoutInflater.from(context); context1=context;
}
public int getCount() { return itemDetailsrrayList.size();
}
public Object getItem(int position) { return itemDetailsrrayList.get(position); }
public long getItemId(int position) {
return position; }
public View getView( final int position, View convertView, ViewGroup parent) {
int ruban=3;
//final ViewHolder holder;
if (convertView == null) {
l_Inflater = LayoutInflater.from(context1);
convertView = l_Inflater.inflate(R.layout.list1, null,true);
}
TextView txt_itemName = (TextView) convertView.findViewById(R.id.textView1); TextView txt_itemDescription = (TextView) convertView.findViewById(R.id.mrp1); TextView txt_itemPrice = (TextView) convertView.findViewById(R.id.ourprice1); TextView txt_itemSave = (TextView) convertView.findViewById(R.id.save1); //holder.txt_itemw = (TextView) convertView.findViewById(R.id.textView4); WebView itemimmm=(WebView)convertView.findViewById(R.id.imageView1); TextView t1 = (TextView) convertView.findViewById(R.id.t1); TextView t2 = (TextView) convertView.findViewById(R.id.t2); TextView t3 = (TextView) convertView.findViewById(R.id.t3); ImageView addprod=(ImageView)convertView.findViewById(R.id.addprod); final Button decprod=(Button)convertView.findViewById(R.id.decprod);
final TextView disprod=(TextView)convertView.findViewById(R.id.disprod); decprod.setVisibility(View.INVISIBLE); disprod.setVisibility(View.INVISIBLE);
txt_itemDescription.setPaintFlags(txt_itemDescription.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); itemimmm.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
txt_itemName.setTypeface(AllItems.face); txt_itemDescription.setTypeface(AllItems.face); txt_itemPrice.setTypeface(AllItems.face); txt_itemSave.setTypeface(AllItems.face); //holder.txt_itemw.setTypeface(AllItems.face); t1.setTypeface(AllItems.rupee);
t2.setTypeface(AllItems.rupee);
t3.setTypeface(AllItems.rupee);
//StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
//StrictMode.setThreadPolicy(policy); txt_itemName.setText(itemDetailsrrayList.get(position).get("name")); txt_itemDescription.setText(itemDetailsrrayList.get(position).get("price")); txt_itemPrice.setText(itemDetailsrrayList.get(position).get("sp"));
txt_itemSave.setText(itemDetailsrrayList.get(position).get("save")); //holder.txt_itemw.setText(itemDetailsrrayList.get(position).get("type"));
itemimmm.loadUrl(itemDetailsrrayList.get(position).get("image")); if(itemDetailsrrayList.get(position).get("name").equals("Daughter")||itemDetailsrrayList.get(position).get("name").equals("Ethnic")) {
Log.e("name", String.valueOf(itemDetailsrrayList.get(position).get("name"))); //decprod.setVisibility(View.VISIBLE); //disprod.setVisibility(View.VISIBLE); }
// Log.e("before", "try");
/* try{
Log.e("try", String.valueOf(itemDetailsrrayList.get(position).get("image")));
Bitmap bitmap1 = BitmapFactory.decodeStream((InputStream) new URL(itemDetailsrrayList.get(position).get("image")).getContent());
itemimmm.setImageBitmap(bitmap1);
}catch(Exception ex){
ex.printStackTrace();
Log.e("error",String.valueOf(ex));
itemimmm.setImageResource(getResources().getIdentifier("ic_launcher", "drawable", getPackageName()));
Log.e("catch", "catch");*/
//prodImage.setImageResource(getResources().getIdentifier("sample", "drawable", getPackageName()));
//itemimmm.setImageResource(getResources().getIdentifier("ic_launcher", "drawable", getPackageName()));
//holder.itemImage.setImageBitmap(bitmap[position]);
addprod.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
//decprod.setVisibility(View.VISIBLE);
//disprod.setVisibility(View.VISIBLE);
/* int k = 0;
if(disprod.getText()!="" || disprod.getText()!=null){
k = Integer.parseInt(String.valueOf(disprod.getText()));
}
disprod.setText(String.valueOf(++k));
disprod.setTag(k);*/
Log.v("position", String.valueOf(position));
new AddCart(decprod,disprod).execute();
} });
decprod.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0)
{
//Log.v("item name", String.valueOf(itemDetailsrrayList.get(position).get("price")));
} });
/* textView.setText(getelement()[position]);
ImageView imageView = (ImageView) convertView
.findViewById(R.id.icon);
imageView.setImageBitmap(bitmap);*/
return convertView;
}
Upvotes: 1