BTMExpert
asked on
JSON Parser in listview in ListFragment
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.
My code works fine on a Activity or ListActivity
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);
}
My code works fine on a Activity or ListActivity
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
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.don e(AsyncTas k.java:299 )
05-16 11:48:48.514: E/AndroidRuntime(801): at java.util.concurrent.Futur eTask.fini shCompleti on(FutureT ask.java:3 52)
05-16 11:48:48.514: E/AndroidRuntime(801): at java.util.concurrent.Futur eTask.setE xception(F utureTask. java:219)
05-16 11:48:48.514: E/AndroidRuntime(801): at java.util.concurrent.Futur eTask.run( FutureTask .java:239)
05-16 11:48:48.514: E/AndroidRuntime(801): at android.os.AsyncTask$Seria lExecutor$ 1.run(Asyn cTask.java :230)
05-16 11:48:48.514: E/AndroidRuntime(801): at java.util.concurrent.Threa dPoolExecu tor.runWor ker(Thread PoolExecut or.java:10 80)
05-16 11:48:48.514: E/AndroidRuntime(801): at java.util.concurrent.Threa dPoolExecu tor$Worker .run(Threa dPoolExecu tor.java:5 73)
05-16 11:48:48.514: E/AndroidRuntime(801): at java.lang.Thread.run(Threa d.java:856 )
05-16 11:48:48.514: E/AndroidRuntime(801): Caused by: java.lang.IllegalStateExce ption: Fragment FragmentsTab3{40dae140} not attached to Activity
05-16 11:48:48.514: E/AndroidRuntime(801): at android.app.Fragment.getRe sources(Fr agment.jav a:762)
05-16 11:48:48.514: E/AndroidRuntime(801): at com.androidbegin.fragmentt abs.Fragme ntsTab3$My AsyncTask. doInBackgr ound(Fragm entsTab3.j ava:94)
05-16 11:48:48.514: E/AndroidRuntime(801): at com.androidbegin.fragmentt abs.Fragme ntsTab3$My AsyncTask. doInBackgr ound(Fragm entsTab3.j ava:1)
05-16 11:48:48.514: E/AndroidRuntime(801): at android.os.AsyncTask$2.cal l(AsyncTas k.java:287 )
05-16 11:48:48.514: E/AndroidRuntime(801): at java.util.concurrent.Futur eTask.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
05-16 11:48:48.514: E/AndroidRuntime(801): java.lang.RuntimeException
05-16 11:48:48.514: E/AndroidRuntime(801): at android.os.AsyncTask$3.don
05-16 11:48:48.514: E/AndroidRuntime(801): at java.util.concurrent.Futur
05-16 11:48:48.514: E/AndroidRuntime(801): at java.util.concurrent.Futur
05-16 11:48:48.514: E/AndroidRuntime(801): at java.util.concurrent.Futur
05-16 11:48:48.514: E/AndroidRuntime(801): at android.os.AsyncTask$Seria
05-16 11:48:48.514: E/AndroidRuntime(801): at java.util.concurrent.Threa
05-16 11:48:48.514: E/AndroidRuntime(801): at java.util.concurrent.Threa
05-16 11:48:48.514: E/AndroidRuntime(801): at java.lang.Thread.run(Threa
05-16 11:48:48.514: E/AndroidRuntime(801): Caused by: java.lang.IllegalStateExce
05-16 11:48:48.514: E/AndroidRuntime(801): at android.app.Fragment.getRe
05-16 11:48:48.514: E/AndroidRuntime(801): at com.androidbegin.fragmentt
05-16 11:48:48.514: E/AndroidRuntime(801): at com.androidbegin.fragmentt
05-16 11:48:48.514: E/AndroidRuntime(801): at android.os.AsyncTask$2.cal
05-16 11:48:48.514: E/AndroidRuntime(801): at java.util.concurrent.Futur
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
ASKER
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;
}
ASKER
here's where I got most of my code from
http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
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?
.... Fragment FragmentsTab3{40dae140} not attached to Activity....
Can you post the complete code?
Have a look here for a possible solution.
ASKER
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
}
}
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;
}
ASKER
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.
ASKER
05-16 20:27:14.926: E/AndroidRuntime(6511): FATAL EXCEPTION: main
05-16 20:27:14.926: E/AndroidRuntime(6511): android.os.NetworkOnMainTh readExcept ion
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.os.StrictMode$Andr oidBlockGu ardPolicy. onNetwork( StrictMode .java:1117 )
05-16 20:27:14.926: E/AndroidRuntime(6511): at java.net.InetAddress.looku pHostByNam e(InetAddr ess.java:3 85)
05-16 20:27:14.926: E/AndroidRuntime(6511): at java.net.InetAddress.getAl lByNameImp l(InetAddr ess.java:2 36)
05-16 20:27:14.926: E/AndroidRuntime(6511): at java.net.InetAddress.getAl lByName(In etAddress. java:214)
05-16 20:27:14.926: E/AndroidRuntime(6511): at org.apache.http.impl.conn. DefaultCli entConnect ionOperato r.openConn ection(Def aultClient Connection Operator.j ava:137)
05-16 20:27:14.926: E/AndroidRuntime(6511): at org.apache.http.impl.conn. AbstractPo olEntry.op en(Abstrac tPoolEntry .java:164)
05-16 20:27:14.926: E/AndroidRuntime(6511): at org.apache.http.impl.conn. AbstractPo oledConnAd apter.open (AbstractP ooledConnA dapter.jav a:119)
05-16 20:27:14.926: E/AndroidRuntime(6511): at org.apache.http.impl.clien t.DefaultR equestDire ctor.execu te(Default RequestDir ector.java :360)
05-16 20:27:14.926: E/AndroidRuntime(6511): at org.apache.http.impl.clien t.Abstract HttpClient .execute(A bstractHtt pClient.ja va:555)
05-16 20:27:14.926: E/AndroidRuntime(6511): at org.apache.http.impl.clien t.Abstract HttpClient .execute(A bstractHtt pClient.ja va:487)
05-16 20:27:14.926: E/AndroidRuntime(6511): at org.apache.http.impl.clien t.Abstract HttpClient .execute(A bstractHtt pClient.ja va:465)
05-16 20:27:14.926: E/AndroidRuntime(6511): at com.example.stupidandroids .JSONParse r.getJSONF romUrlToAr ray(JSONPa rser.java: 88)
05-16 20:27:14.926: E/AndroidRuntime(6511): at com.example.stupidandroids .Videos.on CreateView (Videos.ja va:44)
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.support.v4.app.Fra gment.perf ormCreateV iew(Fragme nt.java:14 60)
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.support.v4.app.Fra gmentManag erImpl.mov eToState(F ragmentMan ager.java: 911)
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.support.v4.app.Fra gmentManag erImpl.mov eToState(F ragmentMan ager.java: 1088)
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.support.v4.app.Bac kStackReco rd.run(Bac kStackReco rd.java:68 2)
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.support.v4.app.Fra gmentManag erImpl.exe cPendingAc tions(Frag mentManage r.java:144 4)
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.support.v4.app.Fra gmentManag erImpl.exe cutePendin gTransacti ons(Fragme ntManager. java:461)
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.support.v4.app.Fra gmentPager Adapter.fi nishUpdate (FragmentP agerAdapte r.java:141 )
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.support.v4.view.Vi ewPager.po pulate(Vie wPager.jav a:1064)
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.support.v4.view.Vi ewPager.po pulate(Vie wPager.jav a:911)
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.support.v4.view.Vi ewPager.on Measure(Vi ewPager.ja va: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.mea sureChildW ithMargins (ViewGroup .java:4825 )
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.widget.FrameLayout .onMeasure (FrameLayo ut.java:31 0)
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.LinearLayou t.measureV ertical(Li nearLayout .java:847)
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.widget.LinearLayou t.onMeasur e(LinearLa yout.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.mea sureChildW ithMargins (ViewGroup .java:4825 )
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.widget.FrameLayout .onMeasure (FrameLayo ut.java:31 0)
05-16 20:27:14.926: E/AndroidRuntime(6511): at com.android.internal.polic y.impl.Pho neWindow$D ecorView.o nMeasure(P honeWindow .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. performMea sure(ViewR ootImpl.ja va:1874)
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.view.ViewRootImpl. measureHie rarchy(Vie wRootImpl. java:1089)
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.view.ViewRootImpl. performTra versals(Vi ewRootImpl .java:1265 )
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.view.ViewRootImpl. doTraversa l(ViewRoot Impl.java: 989)
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.view.ViewRootImpl$ TraversalR unnable.ru n(ViewRoot Impl.java: 4351)
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.view.Choreographer $CallbackR ecord.run( Choreograp her.java:7 49)
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.view.Choreographer .doCallbac ks(Choreog rapher.jav a:562)
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.view.Choreographer .doFrame(C horeograph er.java:53 2)
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.view.Choreographer $FrameDisp layEventRe ceiver.run (Choreogra pher.java: 735)
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.os.Handler.handleC allback(Ha ndler.java :725)
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.os.Handler.dispatc hMessage(H andler.jav a:92)
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.os.Looper.loop(Loo per.java:1 37)
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.app.ActivityThread .main(Acti vityThread .java:5041 )
05-16 20:27:14.926: E/AndroidRuntime(6511): at java.lang.reflect.Method.i nvokeNativ e(Native Method)
05-16 20:27:14.926: E/AndroidRuntime(6511): at java.lang.reflect.Method.i nvoke(Meth od.java:51 1)
05-16 20:27:14.926: E/AndroidRuntime(6511): at com.android.internal.os.Zy goteInit$M ethodAndAr gsCaller.r un(ZygoteI nit.java:7 93)
05-16 20:27:14.926: E/AndroidRuntime(6511): at com.android.internal.os.Zy goteInit.m ain(Zygote Init.java: 560)
05-16 20:27:14.926: E/AndroidRuntime(6511): at dalvik.system.NativeStart. main(Nativ e Method)
Anyone?
05-16 20:27:14.926: E/AndroidRuntime(6511): android.os.NetworkOnMainTh
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.os.StrictMode$Andr
05-16 20:27:14.926: E/AndroidRuntime(6511): at java.net.InetAddress.looku
05-16 20:27:14.926: E/AndroidRuntime(6511): at java.net.InetAddress.getAl
05-16 20:27:14.926: E/AndroidRuntime(6511): at java.net.InetAddress.getAl
05-16 20:27:14.926: E/AndroidRuntime(6511): at org.apache.http.impl.conn.
05-16 20:27:14.926: E/AndroidRuntime(6511): at org.apache.http.impl.conn.
05-16 20:27:14.926: E/AndroidRuntime(6511): at org.apache.http.impl.conn.
05-16 20:27:14.926: E/AndroidRuntime(6511): at org.apache.http.impl.clien
05-16 20:27:14.926: E/AndroidRuntime(6511): at org.apache.http.impl.clien
05-16 20:27:14.926: E/AndroidRuntime(6511): at org.apache.http.impl.clien
05-16 20:27:14.926: E/AndroidRuntime(6511): at org.apache.http.impl.clien
05-16 20:27:14.926: E/AndroidRuntime(6511): at com.example.stupidandroids
05-16 20:27:14.926: E/AndroidRuntime(6511): at com.example.stupidandroids
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.support.v4.app.Fra
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.support.v4.app.Fra
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.support.v4.app.Fra
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.support.v4.app.Bac
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.support.v4.app.Fra
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.support.v4.app.Fra
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.support.v4.app.Fra
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.support.v4.view.Vi
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.support.v4.view.Vi
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.support.v4.view.Vi
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.view.View.measure(
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.view.ViewGroup.mea
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.widget.FrameLayout
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.view.View.measure(
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.widget.LinearLayou
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.widget.LinearLayou
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.view.View.measure(
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.view.ViewGroup.mea
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.widget.FrameLayout
05-16 20:27:14.926: E/AndroidRuntime(6511): at com.android.internal.polic
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.view.View.measure(
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.view.ViewRootImpl.
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.view.ViewRootImpl.
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.view.ViewRootImpl.
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.view.ViewRootImpl.
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.view.ViewRootImpl$
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.view.Choreographer
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.view.Choreographer
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.view.Choreographer
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.view.Choreographer
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.os.Handler.handleC
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.os.Handler.dispatc
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.os.Looper.loop(Loo
05-16 20:27:14.926: E/AndroidRuntime(6511): at android.app.ActivityThread
05-16 20:27:14.926: E/AndroidRuntime(6511): at java.lang.reflect.Method.i
05-16 20:27:14.926: E/AndroidRuntime(6511): at java.lang.reflect.Method.i
05-16 20:27:14.926: E/AndroidRuntime(6511): at com.android.internal.os.Zy
05-16 20:27:14.926: E/AndroidRuntime(6511): at com.android.internal.os.Zy
05-16 20:27:14.926: E/AndroidRuntime(6511): at dalvik.system.NativeStart.
Anyone?
Can you post your full code?
ASKER
Main.java
JSONParser.java
Videos.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;
}
}
}
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;
}
}
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;
}
}
We're also gonna need the xml files.
ASKER
I got it working now
What is the error?