我有一个使用TabHost运行的android应用程序。一旦在MainActivity中获得JSON数据,我想在另一个片段活动中更新并添加图像视图。但当我打电话给shp时。在MainActivity类中添加Images(),应用程序崩溃。请帮助~~
public class MainActivity extends FragmentActivity implements OnTabChangeListener, OnPageChangeListener {
private TabsPagerAdapter mAdapter;
private ViewPager mViewPager;
private TabHost mTabHost;
private String server_url = "http://comicking.blob.core.windows.net/xml/testing.json";
private JSONHandler obj;
private Handler mHandler = new Handler();
ArrayList<Book> bookList;
BookAdapter bookadapter;
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bookList = new ArrayList<Book>();
mViewPager = (ViewPager) findViewById(R.id.viewpager);
InitialiseTabHost();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
mViewPager.setAdapter(mAdapter);
mViewPager.setOnPageChangeListener(MainActivity.this);
new JSONAsyncTask().execute(server_url);
bookadapter = new BookAdapter(getApplicationContext(), R.layout.row, bookList);
Shop shop = new Shop();
shop.AddImages(bookList);
}
@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 boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.Refresh:
//openSearch();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// Method to add a TabHost
private static void AddTab(MainActivity activity, TabHost tabHost, TabHost.TabSpec tabSpec) {
tabSpec.setContent(new MyTabFactory(activity));
tabHost.addTab(tabSpec);
}
// Manages the Tab changes, synchronizing it with Pages
public void onTabChanged(String tag) {
int pos = this.mTabHost.getCurrentTab();
this.mViewPager.setCurrentItem(pos);
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
// Manages the Page changes, synchronizing it with Tabs
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
int pos = this.mViewPager.getCurrentItem();
this.mTabHost.setCurrentTab(pos);
}
@Override
public void onPageSelected(int arg0) {
}
private void InitialiseTabHost() {
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Home").setIndicator("Home"));
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Shop").setIndicator("Shop"));
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Collection").setIndicator("Collection"));
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Help").setIndicator("Help"));
mTabHost.setOnTabChangedListener(this);
}
异步任务类
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
@Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("book");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Book book = new Book();
book.setName(object.getString("name"));
book.setImage(object.getString("img"));
bookList.add(book);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
//bookadapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
碎片类
public class Shop extends Fragment {
public Map<String,Book> shoplist = new HashMap<String,Book>();
private View rootView;
private LinearLayout shopLL;
private Context c;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.shop, container, false);
shopLL = (LinearLayout) rootView.findViewById(R.id.shopLinearLayout);
return rootView;
}
public void AddImages(ArrayList<Book> booklist){
c = getActivity().getApplicationContext();
for(int i = 0; i < booklist.size(); i++){
ImageView img= new ImageView(c);
shopLL.addView(img);
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<TabHost
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<RelativeLayout
android:layout_width="match_parent"
android:id="@+id/linearLayout1"
android:layout_height="match_parent">
<TabWidget
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@android:id/tabs"
android:layout_alignParentBottom="true">
</TabWidget>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@android:id/tabcontent">
</FrameLayout>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="@android:id/tabs"
android:layout_gravity="bottom" />
</RelativeLayout>
</TabHost>
Shop.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<HorizontalScrollView
android:id="@+id/horizontalScrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" >
<LinearLayout
android:id="@+id/shopLinearLayout"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ImageView
android:id="@+id/item1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />
</LinearLayout>
</HorizontalScrollView>
</RelativeLayout>
你能发布你的布局xml吗?假设您在布局文件中定义了"Shop"片段,您可以通过id获得对该片段的引用。然后,您可以使用返回的列表调用Shop片段类上的方法。
Asynctask是你使用的后端服务,你可以返回一个对象而不是布尔
JSONAsyncTask的修改:-
//**** e.g.
class JSONAsyncTask extends AsyncTask<String, Void, JSONObject> {
// define a caller
Shop caller;
//create a Constructor for caller;
public JSONAsyncTask (Shop caller) {
// TODO Auto-generated constructor stub
this.caller = caller;
}
///&& method doInBackground
@Override
protected JSONObject doInBackground(String... urls) {
.....
//custom your returning jsonObject
return jsonobject;
}
////&& return jsonobject back to ur fragment class here by pass in caller
protected void onPostExecute(JSONObject jsonObject) {
caller.onBackgroundTaskCompleted(jsonObject);
}
}
在将MainActivity类方法转换为Shop fragment类的过程中,获取ur json对象:-
@Override
public void onResume() {
new JSONAsyncTask().execute(server_url);
}
//your returning result
public void onBackgroundTaskCompleted(JSONObject result) {
Log.i("TAG", result:"+result);
if(result!=null){
//process your result to get the booklist here
Booklist booklist;
addimage(booklist);
}
}
Gd Luck:)