I cant set my ListView dynamically after getting json response from backend.
SherlockNavigationDrawer extends ActionBarActivity
Activity -
public class Forum extends SherlockNavigationDrawer implements OnClickListener {
AsyncTask<Void, String, Void> forumTask;
ProgressDialog pDialog;
TextView newPost;
Button first, last, next, prev;
ListView list;
LinearLayout nopost;
MyPostListAdapter adapter;
public static final String MyPREFERENCES = "MyPrefs";
SharedPreferences sharedpreferences;
String get = "";
JSONObject json;
JSONParser jp;
JSONArray id, user_id, user_name, date, file_path, description, title,
hut_name, hut_id, ttl_likes, ttl_comment;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.forum);
setTitle("Space Huts | Forum");
// newPost = (TextView) findViewById(R.id.tv_test);
first = (Button) findViewById(R.id.bt_first);
prev = (Button) findViewById(R.id.bt_prev);
next = (Button) findViewById(R.id.bt_next);
last = (Button) findViewById(R.id.bt_last);
list = (ListView) findViewById(R.id.lv_posts);
nopost = (LinearLayout) findViewById(R.id.ll_none);
first.setOnClickListener(this);
prev.setOnClickListener(this);
next.setOnClickListener(this);
last.setOnClickListener(this);
// do a get request to server for getting latest 5 pagination posts
doGETrqst("first");
}
private void doGETrqst(final String page) {
// TODO Auto-generated method stub
forumTask = new AsyncTask<Void, String, Void>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Forum.this);
pDialog.setMessage("Refreshing " + page + " page.....");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
sharedpreferences = getSharedPreferences(MyPREFERENCES,
Context.MODE_PRIVATE);
String usrid = sharedpreferences.getString("sesid", "");
// Create URL string
String URL = "http://xxx.xxx?id="
+ usrid + "&page=" + page;
Log.i("json url ", URL);
try {
jp = new JSONParser();
JSONObject json = jp.getJSONFromUrl(URL);
id = json.getJSONArray("id");
user_id = json.getJSONArray("user_id");
user_name = json.getJSONArray("user_name");
date = json.getJSONArray("date");
file_path = json.getJSONArray("file_path");
description = json.getJSONArray("description");
title = json.getJSONArray("title");
hut_name = json.getJSONArray("hut_name");
hut_id = json.getJSONArray("hut_id");
ttl_likes = json.getJSONArray("ttl_likes");
ttl_comment = json.getJSONArray("ttl_comment");
Log.e("recieved" , id.getString(2));
} catch (Exception ex) {
Log.e("error","error");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
forumTask = null;
pDialog.dismiss();
setListView();
}
};
forumTask.execute(null, null, null);
}
private void setListView() {
// TODO Auto-generated method stub
final List<Posts> listposts = new ArrayList<Posts>();
// create list view arraylist for list adapter
for (int i = 0, length = title.length(); i < length - 1; ++i) {
Posts post = new Posts();
try {
post.setHutname(hut_name.getString(i));
post.setPostname(title.getString(i));
post.setUsername(user_name.getString(i));
post.setDate(date.getString(i));
listposts.add(post);
} catch (JSONException e) {
Toast.makeText(this, "Oooppss connectivity error",
Toast.LENGTH_SHORT).show();
}
}
// if there are new posts to show , remove nopost linear layout
if (listposts.size() > 0) {
nopost.setVisibility(View.GONE);
//set the adapter
adapter = new MyPostListAdapter(listposts , Forum.this );
list.setAdapter(adapter);
}
}
#Override
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.bt_first:
doGETrqst("first");
break;
case R.id.bt_next:
doGETrqst("next");
break;
case R.id.bt_prev:
doGETrqst("prev");
break;
case R.id.bt_last:
doGETrqst("last");
break;
}
}
}
I want to fill my list view dynamically by getting json response from backend , when user press buttons to get next or previous posts.
However there are no errors in logcat , neither the list view is shown .But this part of setListView() do works ,as my linearlayout implements View.GONE successfully -
if (listposts.size() > 0) {
nopost.setVisibility(View.GONE);
//set the adapter
adapter = new MyPostListAdapter(listposts , Forum.this );
list.setAdapter(adapter);
}
XML LAYOUT forum.xml -
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
android:orientation="vertical"
android:weightSum="0" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="20"
android:orientation="vertical" >
<TextView
android:id="#+id/tv_newpost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_gravity="center"
android:background="#drawable/general_buttons"
android:clickable="true"
android:text="New Post"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#drawable/click_text_color"
android:textSize="30dp" />
<LinearLayout
android:id="#+id/ll_none"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:background="#drawable/shadow"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/tv_none"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:fontFamily="sans-serif-thin"
android:text="No New Post"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#000000" />
<ImageView
android:id="#+id/iv_none"
android:layout_width="150dp"
android:layout_height="match_parent"
android:src="#drawable/none" />
</LinearLayout>
<ScrollView
android:id="#+id/sv_posts"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/lv_posts"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:visibility="gone" >
</ListView>
</ScrollView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal" >
<Button
android:id="#+id/bt_first"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:background="#drawable/general_buttons"
android:paddingLeft="15dp"
android:paddingRight="20dp"
android:text="FIRST"
android:textColor="#drawable/click_text_color" />
<Button
android:id="#+id/bt_prev"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/general_buttons"
android:paddingLeft="15dp"
android:paddingRight="20dp"
android:text="<<"
android:textColor="#drawable/click_text_color" />
<Button
android:id="#+id/bt_next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/general_buttons"
android:paddingLeft="20dp"
android:paddingRight="15dp"
android:text=">>"
android:textColor="#drawable/click_text_color" >
</Button>
<Button
android:id="#+id/bt_last"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:background="#drawable/general_buttons"
android:paddingLeft="20dp"
android:paddingRight="15dp"
android:text="LAST"
android:textColor="#drawable/click_text_color" />
</LinearLayout>
</LinearLayout>
After getting responses i updated my code like this -
in onCreate() - before doGETReqst() -
adapter = new MyPostListAdapter(listResults , Forum.this );
list.setAdapter(adapter);
in setListView() -
if (listposts.size() > 0) {
nopost.setVisibility(View.GONE);
//set the adapter
listResults.clear();
listResults.addAll(listposts);
adapter.notifyDataSetChanged();
}
My result is this, now how can i set this into scrollview, in which i nested ListView...i checked my all layouts -
Finally after removing android:view="gone" , adding adapter.notifyDataSetChanged(); and removing scrollview above listview i was able to get this -
Thank you guyz
Your adapter should be created with a List object (for example listResults) and in the setListView do something like:
if (listposts.size() > 0) {
nopost.setVisibility(View.GONE);
//clear old results
listResults.clear();
//load all results
listResults.addAll(listposts);
//notify the adapter about the changes
adapter.notifyDataSetChanged();
}
The point is... create an adapter over an list so... you have ONE instance of that list.
Then update the contents of that list (don't create a new instance), and tell the adapter that the collection has changed.
Try it and let mw know if it works.
In your layout you have android:visibility="gone" set for your listview. I don't see that being toggled in your code.
The answer about updating the adapter instead of creating a new instance is also correct. Initialize your adapter along with your listview and set it (using setAdapter) in the initialization phase. Then when your new data comes in (I modified the code given in the other answer as it was confusing - what's listResults?):
adapter.clear();
//load all results
adapter.addAll(listposts);
//notify the adapter about the changes
adapter.notifyDataSetChanged();
Related
Hi in the below I am displaying operator list displaying using recyclerview.
For this created Table layout contains table row .each row contains data that is coming from server and display via table format.
Response from server:
[{"email":"awdw#dv.vdv","id":"20","mobileNumber":"undefined","username":"akash4345678"}]
But data is displaying in vertial format want to display horizontally.
Expected output:
username email MobileNumber
akash4345678 awdw#dv.vdv undefined
output for below code:
Username Email MobileNumber
akash4345678
awdw#dv.vdv
undefined
Manage_operatorlist.java:
private void doTheAutoRefresh() {
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Write code for your refresh logic
progressDialog = new ProgressDialog (getActivity ());
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Communicating...");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setCancelable(false);
progressDialog.show();
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API.URL_BASE)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client (client)
.build();
API service = retrofit.create (API.class);
Call<List<GetOperatorList>> userCall = service.getopetaorlist ();
userCall.enqueue(new Callback<List<GetOperatorList>> () {
#Override
public void onResponse(Call <List<GetOperatorList>> call, Response <List<GetOperatorList>> response) {
if(response.isSuccessful()) {
progressDialog.dismiss ( );
Log.d ("Response body", new Gson ( ).toJson (response.body ( )));
String Status = new Gson ( ).toJson (response.body ( ));
JSONArray jsonArray = null;
try {
JSONObject jsonObject=null;
jsonArray = new JSONArray (Status);
arrayList = new ArrayList <> ( );
String id;
// String name[]={} ;
for (int i=0;i<jsonArray.length ();i++) {
username=jsonArray.getJSONObject (i).getString ("username");
email=jsonArray.getJSONObject (i).getString ("email");
mobileNumber=jsonArray.getJSONObject (i).getString ("mobileNumber");
//email=jsonArray.getJSONObject (i).getString ("email");
//mobile_number=jsonArray.getJSONObject (i).getString ("MobileNumber");
Typeface typeface = Typeface.createFromAsset(getActivity ().getAssets (), "fonts/astype - Secca Light.otf");
arrayList.add (username);
arrayList.add (email);
arrayList.add (mobileNumber);
// arrayList.add (email);
// arrayList.add (mobile_number);
}
// Creating Adapter object
SwipeRecyclerViewAdapter mAdapter = new SwipeRecyclerViewAdapter((Context) getActivity (), arrayList);
// Setting Mode to Single to reveal bottom View for one item in List
// Setting Mode to Mutliple to reveal bottom Views for multile items in List
((SwipeRecyclerViewAdapter) mAdapter).setMode(Attributes.Mode.Single);
mRecyclerView.setAdapter(mAdapter);
} catch (JSONException e) {
e.printStackTrace ( );
}
}
else {
progressDialog.dismiss ();
Log.d("Response errorBody", String.valueOf(response.errorBody()));
}
}
#Override
public void onFailure(Call<List<GetOperatorList>> call, Throwable t) {
// lv.setAdapter (adapter);
System.out.println("onFailure");
System.out.println(t.fillInStackTrace());
progressDialog.dismiss();
Toast.makeText(getActivity (), "Some error occurred -> ", Toast.LENGTH_LONG).show();;
// progressDialog.dismiss();
}
});
}
}, 5000);
return ;
}
ManageOperatorlist.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/realmsbg">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginTop="20dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:gravity="center_horizontal"
android:background="#drawable/layout_border">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/manage_operator"
android:layout_centerHorizontal="true"
android:padding="12dp"
android:background="#drawable/layout_border"
android:textColor="#fff"
android:textSize="15sp"
android:textStyle="bold"
android:gravity="center"
android:text="Manage Operator List"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TableLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingRight="10dp"
android:paddingLeft="5dp"
android:orientation="horizontal">
<TableRow android:layout_gravity="center_horizontal">
<TextView
android:id="#+id/txtRank"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="top"
android:layout_marginRight="10dp"
android:text="UserName"
android:background="#drawable/cellborder"
android:textColor="#color/color_white"
android:textSize="18sp" />
<TextView
android:id="#+id/txtMovieName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="3dp"
android:layout_gravity="top"
android:layout_marginRight="40dp"
android:text="Email"
android:textColor="#color/color_white"
android:background="#drawable/cellborder"
android:textSize="18sp" />
<TextView
android:id="#+id/txtYear"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="top"
android:text="MobileNumber"
android:textColor="#color/color_white"
android:layout_marginRight="10dp"
android:background="#drawable/cellborder"
android:textSize="18sp" />
</TableRow>
</TableLayout>
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_margin="5dp"
android:layout_weight="1"
android:orientation="horizontal" />
<TextView
android:id="#+id/empty_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="No Records"
android:visibility="gone" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
SwipeAdapter.java:
#Override
public void onBindViewHolder(final SimpleViewHolder viewHolder, final int position) {
int rowPos = viewHolder.getAdapterPosition ();
final String item = String.valueOf (operatorlist.get (position));
String[] strArray = new String[]{item};
System.out.println (strArray);
viewHolder.tvEmail.setText (strArray[0]);
// viewHolder.tvName.setText (strArray[1]);
// String[] strArray1=new String[]{String.valueOf (strArray)};;
// for (int i=0;i<strArray.length;i++){
// strArray1=strArray;
//
//
// // viewHolder.tvEmail.setText (strArray1[1].get());
//
// }
// System.out.println (strArray[1]); //prints "name"
// viewHolder.tvName.setText ((strArray[3]));
// viewHolder.tvEmail.setText (strArray[0]);
// viewHolder.txtRank.setText (strArray[1]);
viewHolder.swipeLayout.setShowMode (SwipeLayout.ShowMode.PullOut);
// Drag From Left
viewHolder.swipeLayout.addDrag (SwipeLayout.DragEdge.Left, viewHolder.swipeLayout.findViewById (R.id.bottom_wrapper1));
// Drag From Right
viewHolder.swipeLayout.addDrag (SwipeLayout.DragEdge.Right, viewHolder.swipeLayout.findViewById (R.id.bottom_wrapper));
// Handling different events when swiping
viewHolder.swipeLayout.addSwipeListener (new SwipeLayout.SwipeListener ( ) {
#Override
public void onClose(SwipeLayout layout) {
//when the SurfaceView totally cover the BottomView.
}
#Override
public void onUpdate(SwipeLayout layout, int leftOffset, int topOffset) {
//you are swiping.
}
#Override
public void onStartOpen(SwipeLayout layout) {
}
#Override
public void onOpen(SwipeLayout layout) {
//when the BottomView totally show.
}
#Override
public void onStartClose(SwipeLayout layout) {
}
#Override
public void onHandRelease(SwipeLayout layout, float xvel, float yvel) {
//when user's hand released.
}
});
please share your SwipeRecyclerViewAdapter and xml .
or you have to update your RecyclerView xml file
In your xml file, TableRow needs to include android:orientation="horizontal", because the default behavior is to layout the text views in vertical.
Apart from that, your TableLayout should have android:orientation="vertical", because otherwise all your rows will appear on a single line.
main_layout.xml
......
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="#+id/linearLayout3"
android:weightSum="1">
<TextView
android:layout_width="180dp"
android:text="TOTAL"
android:layout_height="wrap_content"
android:paddingBottom="5dp"
android:paddingRight="5dp"
android:paddingTop="5dp"
android:layout_gravity="left"
android:layout_weight="0.32"
android:gravity="left|center"
android:paddingLeft="10dp"
android:textColor="#ab330b"></TextView>
<TextView
android:layout_width="220dp"
android:layout_height="wrap_content"
android:id="#+id/total"
android:paddingBottom="5dp"
android:paddingRight="5dp"
android:paddingTop="5dp"
android:layout_gravity="left"
android:layout_weight="0.32"
android:gravity="left|center"
android:paddingLeft="10dp"
android:textColor="#ab330b"></TextView>
</LinearLayout>
.......
GetTotal.class
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
........
sksmkTv = (TextView)findViewById(R.id.TOTSKS);
}
........
........
........
try {
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 kode = c.getString(KDKMK);
String sks = c.getString(SKSMK);
String nil = c.getString(NILMK);
String nmmk = c.getString(NMKMK);
String totalsks = c.getString(TOTSKS);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KDKMK, kode);
map.put(SKSMK, sks);
map.put(NILMK, nil);
map.put(NMKMK, nmmk);
map.put(TOTSKS, totalsks );
// adding HashList to ArrayList
productsList.add(map);
}
}
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(
GetTotal.this, productsList,
R.layout.customgrid_khs, new String[] { NMKMK,
SKSMK, NILMK, TOTSKS },
new int[] { R.id.NMKMK, R.id.SKSMK, R.id.NILMK, R.id.total });
// updating listview
setListAdapter(adapter);
sksmkTv.setText(TOTSKS);
}
});
}
That is a sample of my code.
My list view is working and data from database is showing in the listview.
But I want print value SKSMK at main_layout.xml, not at listview.
What code should I add, to print value SKSMK at android:id="#+id/sksmk"
Thank You.
Firstly,you should handle the TextView in Activity like this:
private TextView sksmkTv;
sksmkTv = (TextView)findViewById(R.id.sksmk);
Then,use a String Object to save the SKSMK value in "try" code block.
at last,set the text in "runOnUiThread"
sksmkTv.setText(sksmkValue);
I am displaying a list of events with an image and various information in a horizontal LinearLayout. I want to start a new Activity upon a user clicking any of the information contained within the LinearLayout.
The Activity displaying the list (EventListActivity) has this .xml file:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#color/crimson"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true">
<LinearLayout
android:id="#+id/event"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:clickable="true"
android:onClick="listItemClick"
android:background="?android:attr/selectableItemBackground" >
<ImageView
android:id="#+id/logo"
android:layout_width="50px"
android:layout_height="50px"
android:layout_marginLeft="5px"
android:layout_marginRight="20px"
android:layout_marginTop="5px"
android:clickable="true"
android:onClick="listItemClick"
android:src="#drawable/alabama" >
</ImageView>
<LinearLayout
android:orientation="vertical"
android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="fill_parent">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="4.85"
android:text="#+id/title"
android:textColor="#color/white"
android:textSize="20px" >
</TextView>
<TextView
android:id="#+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="4.85"
android:text="#+id/date"
android:textColor="#color/white"
android:textSize="10px" >
</TextView>
<TextView
android:id="#+id/venue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="4.85"
android:text="#+id/venue"
android:textColor="#color/white"
android:textSize="10px" >
</TextView>
</LinearLayout>
</LinearLayout>
</ScrollView>
The list is populated in the EventListActivity.java file, with these relevant sections:
public class EventListActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Event[] eventList = null;
try {
eventList = getEventList();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MobileArrayAdapter adapter = new MobileArrayAdapter(this, eventList);
setListAdapter(adapter);
}
public void listItemClick(View view)
{
// launch new Activity
}
public static Event[] getEventList() throws Exception
{
String url = "http://url.com";
String json = new JSONReader().execute(url).get();
JSONArray jsonarr = new JSONArray(json);
// eventually from web service
Event[] eventList = new Event[jsonarr.length()];
for (int i = 0; i < jsonarr.length(); i++)
{
JSONObject jsonobj = jsonarr.getJSONObject(i);
String title = jsonobj.getString("eventName");
String date = "April " + (i+1);
String time = jsonobj.getString("eventTime");
String sport = jsonobj.getString("eventType");
String opponent = jsonobj.getString("opponent");
String venue = jsonobj.getString("eventVenue");
String location = jsonobj.getString("location");
// Location l = new Location(location);
eventList[i] = new Event(title, date, time, sport, opponent, venue, location);
}
return eventList;
}
How can I allow the user to click on any portion of the LinearLayout and launch a new Activity? Originally, I tried to do this with an OnItemClickListener but then realized I'm not using ListView. So then I thought I would do it this way, but the main problem is that the events are populated dynamically and I'm not sure how to specify which event is being clicked, because onClick only takes one parameter, a View. How can I do this?
What you are trying to do seems a really bad code practice. You should use a ListView defining a proper adapter and inflating your row-layout, setting
android:clickable="false"
android:focusable="false"
for each inner widget of the list row
so you can configure properly an onIemClickListener for your list
There are a lot of tutorials in the web... if you are lazy and don't want to Google see this.
When I comment out the code for "nameAdapter = ..." or "numAdapter = ..." and leave the other one uncommented it will display the data in the listview fine. So it is able to display both separately, however, when I leave both uncommented it will only display the data involved with numAdapter. Probably a simple mistake but I can't figure out where I went wrong.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player);
lv = (ListView) findViewById(R.id.listView);
new Logo().execute();
new statistics().execute();
nameAdapter = new ArrayAdapter<String>(this, R.layout.simple_list_item_1, R.id.stat_name,statName);
numAdapter = new ArrayAdapter<String>(this, R.layout.simple_list_item_1, R.id.stat_number,statNum);
}
private class statistics extends AsyncTask<String, Void, String> {
//final ListView listview = (ListView) findViewById(R.id.listView);
/*String[] values = new String[]{ "Ball Control", "Crossing", "Curve",
"Dribbling", "Finishing", "Free Kick Accuracy", "Heading Accuracy", "Long Passing",
"Long Shots", "Marking", "Penalties", "Short Passing", "Shot Power", "Sliding Tackle",
"Standing Tackle", "Volleys"};*/
//String[] stats = new String[16];
#Override
protected String doInBackground(String... arg) {
Document document;
try {
document = Jsoup.connect(url).get();
num = document.select("div#stats-base p");
statNum.clear();
for (Element element : num) {
statNum.add(element.ownText());
}
name = document.select("div#stats-base span");
statName.clear();
for (Element element : name) {
statName.add(element.ownText());
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
lv.setAdapter(nameAdapter);
lv.setAdapter(numAdapter);
}
}
player.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/playerPic"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_below="#+id/playerPic"
android:layout_centerHorizontal="true"
android:layout_marginTop="104dp"/>
</RelativeLayout>
simple_list_item_1.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView android:id="#+id/stat_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dip"
android:textSize="16dip"
android:textStyle="bold"/>
<TextView
android:id="#+id/stat_number"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dip"
android:textSize="16dip"
android:textStyle="bold"
android:layout_below="#id/stat_name"/>
</LinearLayout>
I think there's no mystery in that behavior. The last adapter you set to lv is the one that survives.
If what you're looking for is to add both statName and statNum, I'd set one of them and afterwards use .addAll(...) on the other. For instance:
lv = lv.setAdapter(nameAdapter);
lv.addAll(statNum);
nameAdapter.notifyDataSetChanged();
Don't forget the last line to let your ListView render the new data.
I have an Activity which is called when a listView item is clicked in a fragment.
My problem is that even after i make changes to my layout(setting text of textviews etc) and calling setContentView, the activity screen is blank.
From the Log.i ive used everywhere, in logcat, i can see all data and it is being properly set, so that isnt the problem.
My question is how do i make it so the changes I've made are displayed on screen/How to refresh the layout with the new data.
public class SemListViewActivity extends Activity
{
JSONObject recdJson=new JSONObject();
JSONArray ar;
ArrayList<HashMap<String, String>> keyslist;
TextView semTCredits, semSession, semGPA;
ListView semList;
SemListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
Log.i("Info Tag Sem","Inside Sem");
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.sem_details_listview_layout);
//LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//View v = inflater.inflate(R.layout.sem_details_listview_layout,null);
ar = new JSONArray();
keyslist = new ArrayList<HashMap<String, String>>();
try
{
recdJson = GlobalVars.semJSON;
Log.i("Info Tag Sem","Got the JSON");
ar = recdJson.getJSONArray("seminfo");
Log.i("Info Tag Sem","assigning JSON Array");
for (int i = 0; i < ar.length(); i++)
{
JSONObject jObject = ar.getJSONObject(i);
HashMap<String, String> map = new HashMap<String, String>();
Log.i("Info Tag Sem","jObject Init"+i);
Log.i("Info Tag Sem",jObject.toString());
Log.i("Info Tag Sem",jObject.getString("subcode"));
map.put("subcode", jObject.getString("subcode"));
map.put("sub", jObject.getString("sub"));
map.put("credits", jObject.getString("credits"));
map.put("grade", jObject.getString("grade"));
keyslist.add(map);
}
Log.i("Info Tag Sem","Done with Hashmapping");
semTCredits = (TextView)findViewById(R.id.semTCredits);
semSession = (TextView)findViewById(R.id.semSession);
semGPA = (TextView)findViewById(R.id.semGPA);
Log.i("Info Tag Sem","Set the textviews");
semTCredits.setText("Total Credits: " + recdJson.getString("credits"));
semSession.setText("Session: " + recdJson.getString("session"));
semGPA.setText("Semester GPA: " + recdJson.getString("gpa"));
semList = (ListView)findViewById(R.id.semlist);
adapter = new SemListAdapter(this, keyslist);
semList.setAdapter(adapter);
Log.i("Info Tag Sem","Put the content");
setContentView(R.layout.sem_details_listview_layout);
} catch (JSONException e)
{
e.printStackTrace();
Log.i("Info Tag Sem","Nothing happened ");
}
}
}
and this is the relevant xml layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/semTCredits"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textStyle="bold" />
<TextView
android:id="#+id/semSession"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="2dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textIsSelectable="true" />
<TextView
android:id="#+id/semGPA"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="2dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textIsSelectable="true" />
<ListView
android:id="#+id/semlist"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
Apologies if this question is duplicate, I have no idea how to word my problem.
You are calling setContentView() twice, this second call:
Log.i("Info Tag Sem","Put the content");
setContentView(R.layout.sem_details_listview_layout);
} catch (JSONException e)
erases all of the changes that you made above... Simply remove it.