ArrayAdapter in Fragment - android

I'm beginner in Android Development!
I'm trying insert into Fragment parsing data
Trying to fix error but I have an error "
output cannot be resolved to a variable"
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
ProgressDialog mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setCancelable(false);
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setMessage("Загрузка данных");
mProgressDialog.show();
new ParseSite().execute("http://www.babyblog.ru/magazine/");
View view = inflater.inflate(R.layout.magazine, container, false);
ListView listview = (ListView) view.findViewById(R.id.listViewData);
listview.setAdapter(new ArrayAdapter<String>(getActivity().getApplicationContext(),
android.R.layout.simple_list_item_1 , output));
return view;
}
private class ParseSite extends AsyncTask<String, Void, List<String>> {
protected List<String> doInBackground(String... arg) {
List<String> output = new ArrayList<String>();
try
{
HtmlHelper hh = new HtmlHelper(new URL(arg[0]));
List<TagNode> links = hh.getLinksByClass("razdel-name");
for (Iterator<TagNode> iterator = links.iterator(); iterator.hasNext();)
{
TagNode divElement = (TagNode) iterator.next();
output.add(divElement.getText().toString());
}
}
catch(Exception e)
{
e.printStackTrace();
}
return output;
}
}
}

The variable 'output' has not been defined.
i.e.
listview.setAdapter(new ArrayAdapter<String>(getActivity().getApplicationContext(),
android.R.layout.simple_list_item_1 , output));
That variable is not in scope.
You attemot to use it in onCreate of your fragment, but it is declared in the ASyncTask class.
You need to go and read about ASyncTasks and how you work with them.
http://developer.android.com/guide/components/processes-and-threads.html#WorkerThreads
as a shortcut, try this:
public class YourFragment extends Fragment {
ListView listview;
#Override
public View onCreateView(
// other stuff
listview = (ListView) view.findViewById(R.id.listViewData);
// remove the setAdapater line
}
private class ParseSite extends AsyncTask<String, Void, List<String>> {
// other stuff
protected void onPostExecute(List<String> result) {
listview.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1 , output));
}
}

Your output variable is still null. You have to implement onPostExecute(List result) in your AsyncTask.
This will give you the output you want.
this blogpost can explain how AsyncTask works. But be careful, AsyncTask has a couple of hidden pitfalls. Read all about that here

Related

Android progress dialog not showing in AsyncTask. Blocked UI?

I have an AsyncTask that I'm using to query the database and load a ListView using a custom cursor adapter. The task itself works, but I cannot get the progress dialog to show up.
The async task:
private class LoadListTaskByCursor extends AsyncTask<Void, Void, Cursor> {
private ProgressDialog progressDialog;
private String dictionary;
private Activity activity;
public LoadListTaskByCursor (Activity activity, String dictionary) {
progressDialog = new ProgressDialog(activity);
this.dictionary = dictionary;
this.activity = activity;
}
#Override
protected void onPreExecute() {
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected void onPostExecute(Cursor result) {
ListView lv = (ListView) activity.findViewById(R.id.viewDictionaryList);
lv.setFastScrollEnabled(true);
lv.setAdapter(new CustomTermsCursorAdapter(activity,
R.layout.custom_term_item,
result,
new String[]{getString(R.string.KEY_ID), getString(R.string.KEY_TERM)},
new int[]{R.id.term_item}));
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) parent.getItemAtPosition(position);
// Get the term id from this row in the database.
int termId = cursor.getInt(cursor.getColumnIndexOrThrow(getString(R.string.KEY_ID)));
Bundle bundle = new Bundle();
bundle.putInt("id", termId);
Fragment fragment = new ViewTermFragment();
fragment.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.add(R.id.container, fragment)
.addToBackStack(null)
.commit();
}
});
if(progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
#Override
protected Cursor doInBackground(Void... params) {
Cursor cursor = null;
try {
// do the background process
cursor = db.getAllTermListItemsByDictionaryCursor(getString(R.string.TABLE_TERMS), dictionary);
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
return cursor;
}
}
And I'm call the task from the fragment like this:
LoadListTaskByCursor loadListTaskByCursor = new LoadListTaskByCursor(getActivity(), dictionary);
loadListTaskByCursor.execute();
I've used a similar approach before with a custom array adapter instead of a cursor, and that worked fine. Can anyone tell me what I'm doing wrong? Thanks.
It turns out that my doInBackGround was actually running for a really short amount of time (since it is only returning a cursor) while my onPostExecute was taking really long (due to the setAdapter). The progress dialog was showing up and disappearing without me even noticing.
Thanks to everyone who commented, I appreciate it.

Converting FragmentActivity to a ListFragment with listview -- null pointer exception

I am having issues converting my previously working FragmentActivity and Customlistadapter to a ListFragment to be used with my navigation drawer. Currently, the navigation drawer is working correctly.
Below is the modified code for GetContacts
public class GetContacts extends android.support.v4.app.ListFragment {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// json URL
private static final String url = "http://url.json.php";
private ProgressDialog pDialog;
private List<Contacts> contactList = new ArrayList<Contacts>();
private ListView listView;
private ContactListAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.fragment_contacts, container, false);
return rootview;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
//See the second issue about wotking with ListFragment's list.
adapter = new ContactListAdapter(this, contactList);
setListAdapter(adapter);
// pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
// pDialog.setMessage("Loading...");
//pDialog.show();
// Creating volley request obj
JsonArrayRequest contactReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Contacts contacts = new Contacts();
contacts.setDivision(obj.getString("Division"));
contacts.setName(obj.getString("name"));
contacts.setNumber(obj.getString("number"));
// adding contacts to contacts array
contactList.add(contacts);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(contactReq);
//end volley code paste
}
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
Additionally, I have modified the code for ContactListAdapter. Currently I am getting the following compile error. "Error:(49, 56) error: cannot find symbol method getContext()". I checked this SO question and tried to understand what is causing this issue with no luck.
public class ContactListAdapter extends BaseAdapter {
private Activity activity;
private Fragment fragment;
private LayoutInflater inflater;
private List<Contacts> contactItems;
public ContactListAdapter(Fragment fragment, List<Contacts> contactItems) {
this.fragment = fragment;
this.contactItems = contactItems;
}
#Override
public int getCount() {
return contactItems.size();
}
#Override
public Object getItem(int location) {
return contactItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null){
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_rowcontacts, null);
}
TextView division = (TextView) convertView.findViewById(R.id.division);
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView number = (TextView) convertView.findViewById(R.id.number);
// getting contact data for the row
Contacts m = contactItems.get(position);
// Division
division.setText(m.getDivision());
// Name
name.setText("Name: " + m.getName());
// number
number.setText("Number: " + m.getNumber());
return convertView;
}
}
The main problem is that a FragmentActivity isn't a Fragment, is an Activity (see the reference here). You can't instantiate it as a Fragment like you do in selectItem().
If you want contacts to be loaded in your main activity (the one with the navigation drawer) then GetContacts should inherit from Fragment instead of FragmentActivity.
UPDATE
There are three issues with your code.
Null pointer exception (setting the adapter in the right place)
First you should move everything related to setting up the adapter to a method that is called after the Fragment is attached to its Activity (more info about the Fragment's lifecycle here). In onCreateView the Activity hasn't attached the Fragment yet so the Context of the adapter won't be available (see the third issue). Override onAttach() and place it there:
public class GetContacts extends ListFragment {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// json URL
private static final String url = "http://url.json.php";
private ProgressDialog pDialog;
private List<Contacts> contactList = new ArrayList<Contacts>();
private ListView listView;
public ContactListAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_contacts, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
//See the third issue about the Context passed to the adapter.
adapter = new ContactListAdapter(activity, contactList);
//See the second issue about working with ListFragment's list.
setListAdapter(adapter);
// pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
// pDialog.setMessage("Loading...");
//pDialog.show();
// Creating volley request obj
JsonArrayRequest contactReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Contacts contacts = new Contacts();
contacts.setDivision(obj.getString("Division"));
contacts.setName(obj.getString("name"));
contacts.setNumber(obj.getString("number"));
// adding contacts to contacts array
contactList.add(contacts);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(mcontactReq);
//end volley code paste
}
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
Null pointer exception (working with ListFragment's list
ListFragments provide some methods like setListAdapter() to work with the inner ListView without having to get it first with findViewById(), but they work with their "default" ListView. For identifying this ListView they look in the layout for a ListView with the id #id/android:list. You're using a custom id for your ListView so setListAdapter() cannot find the default ListView (more info about ListFragment here). You have three posible solutions:
First:
If your layout doesn't contain more than a ListView you don't have to use a custom layout. Don't override onCreateView, removing everything about inflating a custom view.
Second:
Change the id of your ListView to #id/android:list in the xml layout file.
Third:
Maintain your custom layout and id, but always use the ListView getting it first with findViewById(), not with the ListFragment's methods for dealing with lists (like when GetContacts was a FragmentActivity). So this:
listView = (ListView) rootView.findViewById(android.R.id.list);
adapter = new ContactListAdapter(this, contactList);
setListAdapter(adapter);
would become this:
listView = (ListView) getView().findViewById(android.R.id.list);
adapter = new ContactListAdapter(this, contactList);
listView.setListAdapter(adapter);
The first two allow you to work with the default list. I don't recomend you to go for the third, since ListFragments are designed for helping you in dealing with lists faster and you wouldn't be using their helper methods, and therefore using a ListFragment like any other Fragment.
P.S. The code for GetContacts I posted before use the second solution.
LayoutInflater in Adapter
With BaseAdapter you have to keep a reference of the Context in wich the adapter will work. Since Fragment isn't a Context, fragments have to use the Activity they're attached to as the Context. Look a this line in the GetContact's code I just updated (in GetContact's onAttached()):
adapter = new ContactListAdapter(activity, contactList);
Then in the adapter you use that as the Context to get the LayoutInflater:
public class ContactListAdapter extends BaseAdapter {
//There is no need for this two
//private Activity activity;
//private Fragment fragment;
//We use this instead
private Context context
private LayoutInflater inflater;
private List<Contacts> contactItems;
//Now the constructor receives a Context
public ContactListAdapter(Context context, List<Contacts> contactItems) {
this.context = context;
this.contactItems = contactItems;
}
//Every other method remains the same
...
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//Now we use context to get the LayoutInflater
if (convertView == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_rowcontacts, null);
}
//The rest of the code is the same
...
}
}
EDIT
Added the changed code for the "set up the adapter in the right place".
Changed the third issue for using a BaseAdapter (I got confused).

How to populate listview in fragment?

I am working on an android application which implements Navigation drawer as its main menu then depending on the choices I do my operations. Now one of the task is to populate a listview from online mysql database host using jdbc. I am able to populate the listview in normal activity but the same code is not working in fragment. This is how my Fragment looks:
public class HomeFragment extends Fragment
{
private ProgressDialog pDialog;
ListView listView ;
Connection conn=null;
ResultSet rs=null;
PreparedStatement st=null;
List<Map<String,String>> list = new ArrayList<Map<String,String>>();
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.main_list, container, false);
try
{
initList();
} catch (SQLException e)
{
e.printStackTrace();
}
String[] from = { "sender", "subject" ,"file_name"};
int[] to = {R.id.sender,R.id.subject,R.id.file_name};
SimpleAdapter adapter = new SimpleAdapter(getActivity(),list,R.layout.list_item,from,to);
//ListView lv=(ListView) rootView.findViewById(R.id.list);
//getListView();
ListView lv= (ListView) getActivity().findViewById(R.id.list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String sender = ((TextView) view.findViewById(R.id.sender)).getText() .toString();
String subject = ((TextView) view.findViewById(R.id.subject)).getText() .toString();
String fname = ((TextView) view.findViewById(R.id.file_name)).getText() .toString();
}
});
return rootView;
}
public void initList() throws SQLException
{
String username="sql428447";
String pass="************";
String sender,subject,file_name;
try
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://sql4.freesqldatabase.com:3306/sql428447",username,pass);
}
catch(Exception x)
{
x.printStackTrace();
}
try
{
String sql="select sender,subject,file_name from files";
st=conn.prepareStatement(sql);
rs=st.executeQuery();
while(rs.next())
{
sender=rs.getString(1);
subject=rs.getString(2);
file_name=rs.getString(3);
list.add(createRecord(sender, subject,file_name));
}
}
catch(Exception z)
{
z.printStackTrace();
}
finally
{
st.close();
rs.close();
}
}
public HashMap<String, String> createRecord(String key, String name,String file_name)
{
HashMap<String, String> record = new HashMap<String, String>();
record.put( "sender", key);
record.put( "subject", name);
record.put("file_name",file_name);
return record;
}
}
and I am calling this fragment from Navigation drawer select item like this:
case 1:
newFragment = new HomeFragment();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
break;
But at runtime in log its throwing exception on line initlist() and st.close() which I am not able to figure out. I guess my approach is almost correct which is discussed in most tutorials but I am not understanding fault in my code cause it is working in normal activity. Any help would be appreciated. Thanks
This is the screenshot of exception
You would probably benefit from using a ListFragment, I've seen many guides on the internet assume you are using one so it can get very confusing.
As for your current error, you're dereferencing st in the finally without verifying it's not null first. If conn throws an error you'll have this happen.
try
{
String sql="select sender,subject,file_name from files";
st=conn.prepareStatement(sql);
rs=st.executeQuery();
while(rs.next())
{
sender=rs.getString(1);
subject=rs.getString(2);
file_name=rs.getString(3);
list.add(createRecord(sender, subject,file_name));
}
}
catch(Exception z)
{
z.printStackTrace();
}
finally
{
if (st != null) {
st.close();
if (rs != null) {
rs.close();
}
}
}
You should have to use ListView lv= (ListView) rootView.findViewById(R.id.list); instead of ListView lv= (ListView) getActivity().findViewById(R.id.list); ... rootView in place of getActivity()

Error in Listview update always stops

i have this listview update:
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
display.elemek.clear();
em1.new AsyncEmBase().execute();
}
}, 0, 1000);
public class AsyncEmBase extends AsyncTask<Void, ListView, Void> {
protected void onPreExecute() {
// display.dataAdapter.clear();
}
#Override
protected Void doInBackground(Void... params) {
readInputRegisters(); /*this only makes display.elemek.add("SomeString")*/
return null;
}
protected void onPostExecute(Void unsed) {
if (display.dataAdapter == null) {
display.dataAdapter = new ArrayAdapter<String>(
display.activity, android.R.layout.simple_list_item_1,
display.elemek);
display.lv.setAdapter(display.dataAdapter);
} else {
display.dataAdapter.notifyDataSetChanged();
}
}
}
it runs smootly but after a while it stops and says:
11-27 15:21:05.769: E/AndroidRuntime(17991): java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. Make sure your adapter calls notifyDataSetChanged() when its content changes. [in ListView(2131296261, class android.widget.ListView) with Adapter(class android.widget.ArrayAdapter)]
i have tried everithing to update the listview but nothing is good.
Please help me!
edit1: new error: Invalid index 7, size is 0
But i clear the elemek arraylist before starting to insert the datas
display.java:
public class display extends Fragment {
public static TextView ain1, ain2, ain3, ain4, dout1, dout2, din1, din2,
din3, din4, cin1, cin2, cin3, cin4, k1, k2, k3, k4, k5, k6, k7, k8;
public static Activity activity;
public static ListView lv;
public static ArrayList<String> elemek;
public static ArrayAdapter<String> dataAdapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.display, container, false);
ain1 = (TextView) rootView.findViewById(R.id.textView2);
activity = getActivity();
lv = (ListView) rootView.findViewById(R.id.listView1);
elemek = new ArrayList<String>();
return rootView;
}
display.activity.runOnUiThread(...) is useless because onPostExecute() is already executed inside the UI thread
and I don't think you have to call notifyDataSetChanged() because you're setting the adapter just before.
Remove all your Thread because you dont need uiThread in onPostExecute() and add like this :
if ( display.dataAdapter == null) {
display.dataAdapter = new ArrayAdapter<String>(
display.activity,
android.R.layout.simple_list_item_1, display.elemek);
display.lv.setAdapter(display.dataAdapter);
}else{
display.dataAdapter.notifyDataSetChanged();
}

Navigate to different pages when a certain LISTVIEW is clicked

I have an android project that gets the values from a remote database. I'm using a listview in eclipse and loops whatever values that my JSON have. Here is my code:
Newsfeed.java
public class NewsFeed extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
private static final String READ_COMMENTS_URL = "http://10.0.2.2/PMR_Drupal/newsfeed.php";
private static final String TAG_TITLE = "trans_name";
private static final String TAG_FOR_A = "sub_trans_name";
private static final String TAG_ACCESS_LEVEL = "ACCESS_LEVEL";
private JSONArray mComments = null;
//manages all of our comments in a list.
private ArrayList<HashMap<String, String>> mCommentList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newsfeed);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_activity_actions, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
//loading the comments via AsyncTask
new LoadComments().execute();
}
public void addComment(View v)
{
Intent i = new Intent("com.pallet.pts.ADDNEWSFEED");
startActivity(i);
}
public void updateJSONdata() {
mCommentList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);
try {
mComments = json.getJSONArray(TAG_POSTS);
for (int i = 0; i < mComments.length(); i++) {
JSONObject c = mComments.getJSONObject(i);
String trans_name = c.getString(TAG_TITLE);
String sub_trans_name = c.getString(TAG_FOR_A);
String ACCESS_LEVEL = c.getString(TAG_ACCESS_LEVEL);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, trans_name);
map.put(TAG_FOR_A, sub_trans_name);
map.put(TAG_ACCESS_LEVEL, ACCESS_LEVEL);
mCommentList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void updateList() {
ListAdapter adapter = new SimpleAdapter(this, mCommentList,
R.layout.single_post, new String[] { TAG_TITLE, TAG_FOR_A, TAG_ACCESS_LEVEL}, new int[] { R.id.title, R.id.forApproval, R.id.count});
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent("com.pallet.pts.NEWSFEED_CLICKED");
intent.putExtra("position", position);
startActivity(intent);
}
});
}
public class LoadComments extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewsFeed.this);
pDialog.setMessage("Checking for Updates...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... arg0) {
//we will develop this method in version 2
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pDialog.dismiss();
//we will develop this method in version 2
updateList();
}
}
}
Now my problem is, since the listview is being looped in, How do I create a listview screen with different content for each row?
Thank you in advance! :D
You need to make an activity which should be blue print for all the activity that will be invoked by ListView .You need to append some values to Intent that you'll be passed to the activity and based on this remaining component can be created dynamically .The way you are doing you will get stuck because the data are coming remote database which may vary time to time.But what I am saying to make a basic skeleton of Activity because most the component will remain same only some of the component may only change which you can add dynamically based on intent valuse
Hello based on the #Shakeeb Shaheen comment here I am trying to write a pseudo-code for you. At first create a xml layout and name it common_layout.xml which will use to show trans and subtrans name. Here is the code of this layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/tv_trans_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/tv_subtrans_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Create an activity for holding this layout.
Now from the NewsFeed activity you have to pass the trans name and subtrans name value when user click on the each list item. You can do this
Intent intent = new Intent(NewsFeed.this, CommonActivity.class);
intent.putExtra("TRANS_NAME", trans_name);
intent.putExtra("SUBTRANS_NAME", subtrans_name);
startActivity(intent);
And then you have to grab these value in your common activity class. This post also can help you how to pass value between two activity.

Categories

Resources