Solved

JSON Parser in listview in ListFragment

Posted on 2013-05-14
14
4,106 Views
Last Modified: 2013-05-20
Is it possible to have a JSON Parser inside a ListFragment?

I've searched the web for hours.  When I run my app, and click on the tab to view the list view, the app crashes.

public class FragmentsTab3 extends ListFragment implements ActionBar.TabListener {
...
JSONParser jParser = new JSONParser();
	        
	        //getting JSON string from URL
	        posts = jParser.getJSONFromUrlToArray(url);

for(int i = 0; i < posts.length(); i++){                        
				    HashMap<String, String> map = new HashMap<String, String>();    
				    JSONObject e = posts.getJSONObject(i);

				    map.put(TAG_TITLE, e.getString(TAG_TITLE));
				    map.put(TAG_VIEWS, e.getString(TAG_VIEWS) + " views");
				    
				    levelList.add(map);            
				}

Open in new window


My code works fine on a Activity or ListActivity
0
Comment
Question by:BTMExpert
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 3
  • 3
14 Comments
 
LVL 17

Accepted Solution

by:
Dejan Pažin earned 500 total points
ID: 39167482
There is no general reason why you couldnt use JSON here. But we need stack trace of the error to see whats wrong. Can you post that?
0
 
LVL 35

Expert Comment

by:girionis
ID: 39170595
When I run my app, and click on the tab to view the list view, the app crashes.

What is the error?
0
 

Author Comment

by:BTMExpert
ID: 39171000
05-16 11:48:48.514: E/AndroidRuntime(801): FATAL EXCEPTION: AsyncTask #1
05-16 11:48:48.514: E/AndroidRuntime(801): java.lang.RuntimeException: An error occured while executing doInBackground()
05-16 11:48:48.514: E/AndroidRuntime(801):       at android.os.AsyncTask$3.done(AsyncTask.java:299)
05-16 11:48:48.514: E/AndroidRuntime(801):       at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
05-16 11:48:48.514: E/AndroidRuntime(801):       at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
05-16 11:48:48.514: E/AndroidRuntime(801):       at java.util.concurrent.FutureTask.run(FutureTask.java:239)
05-16 11:48:48.514: E/AndroidRuntime(801):       at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
05-16 11:48:48.514: E/AndroidRuntime(801):       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
05-16 11:48:48.514: E/AndroidRuntime(801):       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
05-16 11:48:48.514: E/AndroidRuntime(801):       at java.lang.Thread.run(Thread.java:856)
05-16 11:48:48.514: E/AndroidRuntime(801): Caused by: java.lang.IllegalStateException: Fragment FragmentsTab3{40dae140} not attached to Activity
05-16 11:48:48.514: E/AndroidRuntime(801):       at android.app.Fragment.getResources(Fragment.java:762)
05-16 11:48:48.514: E/AndroidRuntime(801):       at com.androidbegin.fragmenttabs.FragmentsTab3$MyAsyncTask.doInBackground(FragmentsTab3.java:94)
05-16 11:48:48.514: E/AndroidRuntime(801):       at com.androidbegin.fragmenttabs.FragmentsTab3$MyAsyncTask.doInBackground(FragmentsTab3.java:1)
05-16 11:48:48.514: E/AndroidRuntime(801):       at android.os.AsyncTask$2.call(AsyncTask.java:287)
05-16 11:48:48.514: E/AndroidRuntime(801):       at java.util.concurrent.FutureTask.run(FutureTask.java:234)
05-16 11:48:48.514: E/AndroidRuntime(801):       ... 4 more
05-16 11:48:52.913: D/dalvikvm(801): GC_CONCURRENT freed 413K, 14% free 3509K/4052K, paused 4ms+7ms, total 65ms
05-16 11:48:52.943: D/dalvikvm(801): WAIT_FOR_CONCURRENT_GC blocked 64ms
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:BTMExpert
ID: 39171006
Here's where I try to parse the JSON url

@Override
	    protected ArrayList<HashMap<String, String>>doInBackground(String... params) {

	        //Creating JSON Parser instance
	        JSONParser jParser = new JSONParser();
	        
	        //getting JSON string from URL
	     // Making HTTP request
			try {
				// defaultHttpClient
				DefaultHttpClient httpClient = new DefaultHttpClient();
				HttpGet httpGet = new HttpGet(url);

				HttpResponse httpResponse = httpClient.execute(httpGet);
				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 {
				post = new JSONArray(json);
			} catch (JSONException e) {
				Log.e("JSON Parser", "Error parsing data " + e.toString());
			}
	       
	        String[] adobe_products = getResources().getStringArray(R.array.adobe_products);
	        
	        for(int i = 0; i < adobe_products.length; i++){                        
			    HashMap<String, String> map = new HashMap<String, String>();    

			    map.put(TAG_TITLE, adobe_products[i]);
			    
			    levelList.add(map);            
			}
	        

	        return levelList;

	    }

Open in new window

0
 

Author Comment

by:BTMExpert
ID: 39171017
0
 
LVL 17

Expert Comment

by:Dejan Pažin
ID: 39171049
It doesnt look like JSON error - it states that you have a problem with a Fragment:

.... Fragment FragmentsTab3{40dae140} not attached to Activity....

Can you post the complete code?
0
 
LVL 35

Expert Comment

by:girionis
ID: 39171068
Have a look here for a possible solution.
0
 

Author Comment

by:BTMExpert
ID: 39171070
public class FragmentsTab3 extends ListFragment implements ActionBar.TabListener {

	private Fragment mFragment;
	//YouTube
	private static final String TAG_TITLE = "title";
	private static final String TAG_VIEWS = "views";
	//JSON Node names (level, sensorID, value)
	//pspace JSONArray

	private static String url = "secret url but just a basic json format like twitter";
	JSONArray posts = null;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment3, container, false);
	}
	public void onStart() {
        super.onStart();
        new MyAsyncTask().execute();
	}

	class MyAsyncTask extends AsyncTask<String, Integer, ArrayList<HashMap<String, String>> > {

	    //Hashmap for ListView
	    ArrayList<HashMap<String, String>> levelList = new ArrayList<HashMap<String, String>>();

	    @Override
	    protected ArrayList<HashMap<String, String>>doInBackground(String... params) {

	        //Creating JSON Parser instance
	        JSONParser jParser = new JSONParser();
	        
	        try {
				// Getting Array
				posts = jParser.getJSONFromUrlToArray(url);
			
				for(int i = 0; i < posts.length(); i++){                        
				    HashMap<String, String> map = new HashMap<String, String>();    
				    JSONObject e = posts.getJSONObject(i);

				    map.put(TAG_TITLE, e.getString(TAG_TITLE));
				    map.put(TAG_VIEWS, e.getString(TAG_VIEWS) + " views");
				    
				    levelList.add(map);            
				}
				
		
			} catch (JSONException e) {
				e.printStackTrace();
			}
	        return levelList;

	    }

	    @Override
	    protected void onPostExecute(ArrayList<HashMap<String, String>> levelList) {

	        ListAdapter adapter = new SimpleAdapter(getActivity(), levelList, R.layout.youtube_list, new String[] { TAG_TITLE }, new int[] {
				R.id.title });
	        setListAdapter(adapter);

	    }

	}

	
	public void onTabSelected(Tab tab, FragmentTransaction ft) {
		// TODO Auto-generated method stub
		mFragment = new FragmentsTab3();
		// Attach fragment3.xml layout
		ft.add(android.R.id.content, mFragment);
		ft.attach(mFragment);
	}

	public void onTabUnselected(Tab tab, FragmentTransaction ft) {
		// TODO Auto-generated method stub
		// Remove fragment3.xml layout
		ft.remove(mFragment);
	}

	public void onTabReselected(Tab tab, FragmentTransaction ft) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		
		
	}

	public void onListItemClick(ListView l, View v, int position, long id) {
		// Do something with the data

	}
}

Open in new window


I have a JSONParser class with this function in it

public JSONArray getJSONFromUrlToArray(String url) {

		
		// Making HTTP request
		try {
			// defaultHttpClient
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(url);

			HttpResponse httpResponse = httpClient.execute(httpGet);
			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 {
			jObjA = new JSONArray(json);
		} catch (JSONException e) {
			Log.e("JSON Parser", "Error parsing data " + e.toString());
		}
		// return JSON String
		return jObjA;

	}

Open in new window

0
 

Author Comment

by:BTMExpert
ID: 39172248
I still get an error.  I tried to start over with the slide tab template and I still get the same crashing and error.  Is there an example of a listfragment and json that works?  If I use a static array for my listview it works fine.  If i use json on a list activity it works fine.  list fragment crashes.
0
 

Author Comment

by:BTMExpert
ID: 39172825
05-16 20:27:14.926: E/AndroidRuntime(6511): FATAL EXCEPTION: main
05-16 20:27:14.926: E/AndroidRuntime(6511): android.os.NetworkOnMainThreadException
05-16 20:27:14.926: E/AndroidRuntime(6511):       at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at java.net.InetAddress.getAllByName(InetAddress.java:214)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at com.example.stupidandroids.JSONParser.getJSONFromUrlToArray(JSONParser.java:88)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at com.example.stupidandroids.Videos.onCreateView(Videos.java:44)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at android.support.v4.app.Fragment.performCreateView(Fragment.java:1460)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:911)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:461)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at android.support.v4.view.ViewPager.populate(ViewPager.java:1064)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at android.support.v4.view.ViewPager.populate(ViewPager.java:911)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1432)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at android.view.View.measure(View.java:15518)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at android.view.View.measure(View.java:15518)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at android.widget.LinearLayout.measureVertical(LinearLayout.java:847)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at android.view.View.measure(View.java:15518)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2176)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at android.view.View.measure(View.java:15518)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1874)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1089)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1265)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at android.view.Choreographer.doCallbacks(Choreographer.java:562)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at android.view.Choreographer.doFrame(Choreographer.java:532)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at android.os.Handler.handleCallback(Handler.java:725)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at android.os.Handler.dispatchMessage(Handler.java:92)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at android.os.Looper.loop(Looper.java:137)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at android.app.ActivityThread.main(ActivityThread.java:5041)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at java.lang.reflect.Method.invokeNative(Native Method)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at java.lang.reflect.Method.invoke(Method.java:511)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-16 20:27:14.926: E/AndroidRuntime(6511):       at dalvik.system.NativeStart.main(Native Method)




Anyone?
0
 
LVL 35

Expert Comment

by:girionis
ID: 39173862
Can you post your full code?
0
 

Author Comment

by:BTMExpert
ID: 39174375
Main.java
import java.util.Locale;

import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class MainActivity extends FragmentActivity implements
		ActionBar.TabListener {

	/**
	 * The {@link android.support.v4.view.PagerAdapter} that will provide
	 * fragments for each of the sections. We use a
	 * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
	 * will keep every loaded fragment in memory. If this becomes too memory
	 * intensive, it may be best to switch to a
	 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
	 */
	SectionsPagerAdapter mSectionsPagerAdapter;

	/**
	 * The {@link ViewPager} that will host the section contents.
	 */
	ViewPager mViewPager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// Set up the action bar.
		final ActionBar actionBar = getActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

		// Hide Actionbar Icon
		actionBar.setDisplayShowHomeEnabled(false);

		// Hide Actionbar Title
		actionBar.setDisplayShowTitleEnabled(false);

		// Create the adapter that will return a fragment for each of the three
		// primary sections of the app.
		mSectionsPagerAdapter = new SectionsPagerAdapter(
				getSupportFragmentManager());

		// Set up the ViewPager with the sections adapter.
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setAdapter(mSectionsPagerAdapter);

		// When swiping between different sections, select the corresponding
		// tab. We can also use ActionBar.Tab#select() to do this if we have
		// a reference to the Tab.
		mViewPager
				.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
					@Override
					public void onPageSelected(int position) {
						actionBar.setSelectedNavigationItem(position);
					}
				});

		// Create first Tab
		actionBar.addTab(actionBar.newTab()
				.setText("Videos")
				.setTabListener(this));

		// For each of the sections in the app, add a tab to the action bar.
		for (int i = 1; i < mSectionsPagerAdapter.getCount(); i++) {
			// Create a tab with text corresponding to the page title defined by
			// the adapter. Also specify this Activity object, which implements
			// the TabListener interface, as the callback (listener) for when
			// this tab is selected.
			actionBar.addTab(actionBar.newTab()
					.setText(mSectionsPagerAdapter.getPageTitle(i))
					.setTabListener(this));
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public void onTabSelected(ActionBar.Tab tab,
			FragmentTransaction fragmentTransaction) {
		// When the given tab is selected, switch to the corresponding page in
		// the ViewPager.
		mViewPager.setCurrentItem(tab.getPosition());
	}

	@Override
	public void onTabUnselected(ActionBar.Tab tab,
			FragmentTransaction fragmentTransaction) {
	}

	@Override
	public void onTabReselected(ActionBar.Tab tab,
			FragmentTransaction fragmentTransaction) {
	}

	/**
	 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
	 * one of the sections/tabs/pages.
	 */
	public class SectionsPagerAdapter extends FragmentPagerAdapter {

		public SectionsPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			// getItem is called to instantiate the fragment for the given page.
			// Return a DummySectionFragment (defined as a static inner class
			// below) with the page number as its lone argument.
			if(position > 0) {
			System.out.println(position);
			Fragment fragment = new DummySectionFragment();
			Bundle args = new Bundle();
			args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
			fragment.setArguments(args);
			
			return fragment;
			} else {
				Fragment fragment = new Videos();
				return fragment;
			}
		}

		@Override
		public int getCount() {
			// Show 3 total pages.
			return 3;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			Locale l = Locale.getDefault();
			switch (position) {
			case 0:
				return getString(R.string.title_section1).toUpperCase(l);
			case 1:
				return getString(R.string.title_section2).toUpperCase(l);
			case 2:
				return getString(R.string.title_section3).toUpperCase(l);
			case 3:
				return getString(R.string.title_section4).toUpperCase(l);
			case 4:
				return getString(R.string.title_section5).toUpperCase(l);
			}

			return null;
		}
	}

	/**
	 * A dummy fragment representing a section of the app, but that simply
	 * displays dummy text.
	 */
	public static class DummySectionFragment extends Fragment {
		/**
		 * The fragment argument representing the section number for this
		 * fragment.
		 */
		public static final String ARG_SECTION_NUMBER = "section_number";

		public DummySectionFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_main_dummy,
					container, false);
			TextView dummyTextView = (TextView) rootView
					.findViewById(R.id.section_label);
			dummyTextView.setText(Integer.toString(getArguments().getInt(
					ARG_SECTION_NUMBER)));
			return rootView;
		}
	}
	
	

}

Open in new window



JSONParser.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;


import android.util.Log;

public class JSONParser {

	static InputStream is = null;
	static JSONObject jObj = null;
	static JSONArray jObjA = null;
	static String json = "";

	// constructor
	public JSONParser() {

	}

public JSONObject getJSONFromUrl(String url) {
        
        // Making HTTP request
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
 
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();            
 
        } catch (UnsupportedEncodingException exception) {
            exception.printStackTrace();
        } catch (ClientProtocolException exception) {
            exception.printStackTrace();
        } catch (IOException exception) {
            exception.printStackTrace();
        }
        
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sBuilder = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sBuilder.append(line + "\n");
            }
            is.close();
            json = sBuilder.toString();
        } catch (Exception exception) {
            exception.printStackTrace();
        }
 
        // Parsing the string to a JSON object
        try {
        	jObj = new JSONObject(json);
        } catch (JSONException exception) {
            exception.printStackTrace();
        }
 
        // JSON String
        return jObj;
 
    }

	public JSONObject getJSONFromUrlToObject(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;

	}
	
	public JSONArray getJSONFromUrlToArray(String url) {

		
		// Making HTTP request
		try {
			// defaultHttpClient
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(url);

			HttpResponse httpResponse = httpClient.execute(httpGet);
			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 {
			jObjA = new JSONArray(json);
		} catch (JSONException e) {
			Log.e("JSON Parser", "Error parsing data " + e.toString());
		}
		// return JSON String
		return jObjA;

	}
	
	
}

Open in new window


Videos.java
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.support.v4.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class Videos extends Fragment {
	/**
	 * The fragment argument representing the section number for this
	 * fragment.
	 */
	private static final String TAG_TITLE = "title";
	private static final String TAG_VIEWS = "views";
	private ArrayList<HashMap<String, Object>> filterListData;
    private ListView filterListView;
	private static String url = "json formatted webpage like twitter";
	JSONArray posts = null;
	private ArrayList<HashMap<String, String>> levelList = new ArrayList<HashMap<String, String>>();

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.video_list,
				container, false);

		filterListView = (ListView) rootView.findViewById(R.id.list);
		new LoadJsonTask().execute(url);

		return rootView;
	}
	
	private class LoadJsonTask extends AsyncTask<String, Void, ArrayList<HashMap<String, String>> > {
	       protected ArrayList<HashMap<String, String>> doInBackground (String... params){
	           return doGetJson(params[0]);
	       }


	    @Override
	    protected void onPostExecute(ArrayList<HashMap<String, String>> levelList) {
	    	if(isAdded()){
	            getResources().getString(R.string.app_name);
	            ListAdapter adapter = new SimpleAdapter(getActivity(), levelList, R.layout.youtube_list, new String[] { TAG_TITLE, TAG_VIEWS }, new int[] {
					R.id.title, R.id.views });
	            filterListView.setAdapter(adapter);
	        }
	        

	    }

	}
	
	public ArrayList<HashMap<String, String>> doGetJson(String url) {
		JSONParser jParser = new JSONParser();
        
		try {
			// Getting Array
			posts = jParser.getJSONFromUrlToArray(url);
			
			for(int i = 0; i < posts.length(); i++){                        
			    HashMap<String, String> map = new HashMap<String, String>();    
			    JSONObject e = posts.getJSONObject(i);

			    map.put(TAG_TITLE, e.getString(TAG_TITLE));
			    map.put(TAG_VIEWS, e.getString(TAG_VIEWS) + " views");
			    
			    levelList.add(map);            
			}
			
	
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		return levelList;
	
	}
}

Open in new window

0
 
LVL 17

Expert Comment

by:Dejan Pažin
ID: 39176993
We're also gonna need the xml files.
0
 

Author Closing Comment

by:BTMExpert
ID: 39181351
I got it working now
0

Featured Post

[Webinar] Code, Load, and Grow

Managing multiple websites, servers, applications, and security on a daily basis? Join us for a webinar on May 25th to learn how to simplify administration and management of virtual hosts for IT admins, create a secure environment, and deploy code more effectively and frequently.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

This is an explanation of a simple data model to help parse a JSON feed
If you use the Google Now Launcher, as an aftermarket add on, have a Samsung Note 5 and are worried about power consumption be wary of using the ultra power saving mode.  Here is what happened to me when I made the mistake of trying this out...
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Suggested Courses

739 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question