ListActivity in SherlockListFragment abrufen

  • Antworten:1
JmAndroid
  • Forum-Beiträge: 1

17.04.2014, 13:09:51 via Website

Hallo Leute, ich bin ein frischling in Java und der Android Entwicklung.

Probiere gerade etwas herum und habe bereits ein MySQL abruf hinbekommen. Nun möchte ich diese in einem TabSwipe Menu (SherlockActionBar) abrufen, Ich bin nach folgenden Tutorial gegangen: "htt_p://wptrafficanalyzer.in/blog/implement-swiping-between-tabs-with-viewpager-in-action-bar-using-sherlock-library/"

Ich habe nun ein drittes Tab hinzugefügt und es StoreFragment genannt. Nun möchte ich in diesem Tab Die Seite AllStoresActvity aufrufen.

Bitte um Hilfe.

public class AllStoresActivity extends ListActivity {

// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> productsList;

// url to get all products list
private static String url_all_products = "server link";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_STREET = "street";

// products JSONArray
JSONArray products = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.all_stores);

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

    // Loading products in Background Thread
    new LoadAllProducts().execute();

    // Get listview
    ListView lv = getListView();

    // on seleting single product
    // launching Edit Product Screen
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            String pid = ((TextView) view.findViewById(R.id.pid)).getText()
                    .toString();

            // Starting new intent
            Intent in = new Intent(getApplicationContext(),
                    DetailStoreActivity.class);
            // sending pid to next activity
            in.putExtra(TAG_PID, pid);

            // starting new activity and expecting some response back
            startActivityForResult(in, 100);
        }
    });

}

// Response from Edit Product Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // if result code 100
    if (resultCode == 100) {
        // if result code 100 is received 
        // means user edited/deleted product
        // reload this screen again
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }

}

/**
 * Background Async Task to Load all product by making HTTP Request
 * */
class LoadAllProducts extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(AllStoresActivity.this);
        pDialog.setMessage("Loading products. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting All products from url
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

        // Check your log cat for JSON reponse
        Log.d("All Products: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // products found
                // Getting Array of Products
                products = json.getJSONArray(TAG_PRODUCTS);

                // looping through All Products
                for (int i = 0; i < products.length(); i++) {
                    JSONObject c = products.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(TAG_PID);
                    String name = c.getString(TAG_NAME);
                    String street = c.getString(TAG_STREET);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_PID, id);
                    map.put(TAG_NAME, name);
                    map.put(TAG_STREET, street);

                    // adding HashList to ArrayList
                    productsList.add(map);
                }
            } else {
                // no products found
                // Launch Add New product Activity
                Intent i = new Intent(getApplicationContext(),
                        NewStoreActivity.class);
                // Closing all previous activities
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        AllStoresActivity.this, productsList,
                        R.layout.list_item, new String[] { TAG_PID,
                                TAG_NAME, TAG_STREET},
                        new int[] { R.id.pid, R.id.name, R.id.street });
                // updating listview
                setListAdapter(adapter);
            }
        });

    }

}

Das ist meine MainActivity.java

public class MainActivity extends SherlockFragmentActivity {
ActionBar mActionBar;
ViewPager mPager;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_main);

    /** Getting a reference to action bar of this activity */
    mActionBar = getSupportActionBar();

    /** Set tab navigation mode */
    mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    /** Getting a reference to ViewPager from the layout */
    mPager = (ViewPager) findViewById(R.id.pager);

    /** Getting a reference to FragmentManager */
    FragmentManager fm = getSupportFragmentManager();

    /** Defining a listener for pageChange */
    ViewPager.SimpleOnPageChangeListener pageChangeListener = new ViewPager.SimpleOnPageChangeListener(){
        @Override
        public void onPageSelected(int position) {
            super.onPageSelected(position);
            mActionBar.setSelectedNavigationItem(position);
        }
    };

    /** Setting the pageChange listner to the viewPager */
    mPager.setOnPageChangeListener(pageChangeListener);

    /** Creating an instance of FragmentPagerAdapter */
    MyFragmentPagerAdapter fragmentPagerAdapter = new MyFragmentPagerAdapter(fm);

    /** Setting the FragmentPagerAdapter object to the viewPager object */
    mPager.setAdapter(fragmentPagerAdapter);

    mActionBar.setDisplayShowTitleEnabled(true);

    /** Defining tab listener */
    ActionBar.TabListener tabListener = new ActionBar.TabListener() {

        @Override
        public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        }

        @Override
        public void onTabSelected(Tab tab, FragmentTransaction ft) {
            mPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabReselected(Tab tab, FragmentTransaction ft) {
        }
    };

    /** Creating Android Tab */
    Tab tab = mActionBar.newTab()
            .setText("Android")
            .setIcon(R.drawable.android)
            .setTabListener(tabListener);

    mActionBar.addTab(tab);

    /** Creating Apple Tab */
    tab = mActionBar.newTab()
            .setText("Apple")
            .setIcon(R.drawable.apple)
            .setTabListener(tabListener);

    mActionBar.addTab(tab);

    /** Creating Stores Tab */
    tab = mActionBar.newTab()
            .setText("Stores")
            .setIcon(R.drawable.apple)
            .setTabListener(tabListener);

    mActionBar.addTab(tab);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getSupportMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

Das ist meine MyFragmentPagerAdapter.java

public class MyFragmentPagerAdapter extends FragmentPagerAdapter{

final int PAGE_COUNT = 3;

/** Constructor of the class */
public MyFragmentPagerAdapter(FragmentManager fm) {
    super(fm);
}

/** This method will be invoked when a page is requested to create */
@Override
public Fragment getItem(int arg0) {
    Bundle data = new Bundle();
    switch(arg0){
        /** Android tab is selected */
        case 0:
            AndroidFragment androidFragment = new AndroidFragment();
            data.putInt("current_page", arg0+1);
            androidFragment.setArguments(data);
            return androidFragment;

        /** Apple tab is selected */
        case 1:
            AppleFragment appleFragment = new AppleFragment();
            data.putInt("current_page", arg0+1);
            appleFragment.setArguments(data);
            return appleFragment;
        case 2:
            StoreFragment storeFragment = new StoreFragment();
            data.putInt("current_page", arg0+1);
            storeFragment.setArguments(data);
            return storeFragment;
    }
    return null;
}

/** Returns the number of pages */
@Override
public int getCount() {
    return PAGE_COUNT;
}

}

Also ich möchte, wenn man auf den Stores Tab klickt sich die AllStoresActivity öffnet. :-)

Antworten
impjor
  • Forum-Beiträge: 1.793

17.04.2014, 18:03:44 via App

Wo ist denn dein Problem? Du hast zwar ellenlangen Code gepostet, aber nicht dein Problem benannt. Weißt du nicht wie man eine Activity erstellt / aufruft? Weißt du nicht wie man auf das klicken eines Tab's reagieren kann? Mit ein wenig Eigeninitiative sollte man das schnell ergooglen können oder hier zumindest Ansätze, die vielleicht noch nicht korrekt funktionieren.

Liebe Grüße impjor.

Für ein gutes Miteinander: Unsere Regeln
Apps für jeden Einsatzzweck
Stellt eure App vor!

Antworten