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.
Related
I am working on a application and making an http request which works fine ,
this is my Asynch class Doinbackground method:
#Override
protected String doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.d("Response ==>", "Response from url: ");
longInfo(jsonStr);
return jsonStr;
}
this is the logic i am using
public void longInfo(String str) {
if(str.length() > 4000) {
Log.e("TAG", str.substring(0, 4000));
longInfo(str.substring(4000));
} else
Log.e("TAG", str);
}
but this gives me chunks of json string which breaks json format and i am unable to parse objects and arrays accordingly. kindly help
here is my parsing method of json
public void parsejsonp(String jsonp){
if (jsonp != null) {
try {
JSONObject jsonObj = new JSONObject(jsonp);
int count = jsonObj.getInt("count");
Log.e("count=> ",count+"");
int count_total = jsonObj.getInt("count_total");
Log.e("count_total=> ",count_total+"");
int pages = jsonObj.getInt("pages");
Log.e("pages=> ",pages+"");
// Getting JSON Array node
JSONArray Posts = jsonObj.getJSONArray("posts");
// looping through All Posts
for (int i = 0; i < Posts.length(); i++) {
JSONObject c = Posts.getJSONObject(i);
String id = c.getString("id");
String type = c.getString("type");
String slug = c.getString("slug");
String status = c.getString("status");
String title = c.getString("title");
String title_plain = c.getString("title_plain");
String content = c.getString("content");
String date = c.getString("date");
String modified = c.getString("modified");
// Phone node is JSON Object
// JSONObject phone = c.getJSONObject("phone");
// String mobile = phone.getString("mobile");
// String home = phone.getString("home");
// String office = phone.getString("office");
// tmp hash map for single contact
HashMap<String, String> posting = new HashMap<>();
// adding each child node to HashMap key => value
posting.put("id", id);
posting.put("type", type);
posting.put("slug", slug);
posting.put("status",status);
posting.put("title", title);
posting.put("content", content);
posting.put("date", date);
posting.put("modified", modified);
// adding contact to contact list
postList.add(posting);
}
} catch (final JSONException e) {
Log.e("error", "Json parsing error: " + e.getMessage());
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e("er server", "Couldn't get json from server.");
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
}
this is my onPost method:
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.e("RESULT",result);
parsejsonp(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
getActivity(), postList,
R.layout.list_item2, new String[]{"type", "slug","status",
"title","content","date","modified"}, new int[]{R.id.type,
R.id.slug,R.id.state_p,R.id.title_p, R.id.content,R.id.date_p,R.id.moddate_p});
lv.setAdapter(adapter);
}
but still i am unable to parse all the data because still in my onPost method in result parameter i am not having complete response
i have also checked the url on browser the response is showing completely there.
but if it is not shown completely in logcat due to buffer size it must put all the data in my listview but it is not
here is the screen shot of my listview
as you can see only one object data is inserted but rest of the response is not inserted , i have debugged all the code and checked the arraylist size it is storing complete number of objects , but my screen seems to show only one object data :
here is my layout.xml file may be the problem is here :
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".fragment">
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="fill_vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<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"
tools:context="com.adnan.zwd.hidoctor.Patient.Frag_two">
<ListView
android:id="#+id/list2"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
</android.support.v4.widget.NestedScrollView>
</RelativeLayout>
row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="#dimen/activity_horizontal_margin">
<TextView
android:id="#+id/type"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:text="type"
android:textColor="#color/colorPrimaryDark"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/slug"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="slug"
android:paddingBottom="2dip"
android:textColor="#color/colorAccent" />
<TextView
android:id="#+id/state_p"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="status"
android:paddingBottom="2dip"
android:textColor="#color/colorAccent" />
<TextView
android:id="#+id/title_p"
android:text="title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold" />
<TextView
android:id="#+id/content"
android:text="content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold" />
<TextView
android:id="#+id/date_p"
android:text="date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold" />
<TextView
android:id="#+id/moddate_p"
android:text="Mod Date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold" />
</LinearLayout>
Any help regarding this issue , i searched a lot on internet but no success
and it gives exception for parsing.
What exception? Here maybe?
new JSONObject(str.substring(4000));
You can't just cut the middle of a JSONObject. The first { or [ character matters.
You can use the JsonReader class to parse the InputStream instead of reading the stream to a BufferedReader, then a string.
Or...
You aren't meant to parse from that method. The string is already in memory in order to get passed into that method.
#Override
protected String doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.d("Response ==>", "Response from url: ");
longInfo(jsonStr);
return jsonStr; // change your AsyncTask from Void to String return type
}
// standalone method
public static void longInfo(String str) {
if(str.length() > 4000) {
Log.i(TAG, str.substring(0, 4000));
longInfo(str.substring(4000));
} else
Log.i(TAG, str);
}
here is my layout.xml file may be the problem is here
Yup, there is an issue there.
You should never use a ScrollView with a ListView, because ListView takes care of its own vertical scrolling
Android | ScrollView
This is all you need for a Fragment layout
<?xml version="1.0" encoding="utf-8"?>
<ListView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/list2"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
Finally i found the problem . It was all happening because of android.support.v4.widget.NestedScrollView in my layout
and i solved it by adding android:fillViewport="true" attribute in nestedscrollview
as mentioned here :
ListView not expanding inside NestedScrollView
GoTo Android_Studio_Path\bin\idea.properties
Change the BufferSize and increase it to 2048
idea.cycle.buffer.size=1024
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();
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 a activity which takes data from server and add to a array list. I have an xml layout "list_item". I want to set the logo on top of that list. But if I added logo on that xml file, the logo shows with every list item. But I need the logo only one(on top of the list).
Here is the activity:
public class CampaignActivity extends ListActivity {
Button sub;
NotificationManager nm;
TextView campaign;
static final int uniqueId=12;
static InputStream is = null;
private static final String TAG_ID = "_id";
private static final String TAG_NAME = "name";
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
//setContentView(R.layout.campaign);
//campaign = (TextView) findViewById(R.id.textView1);
//sub = (Button) findViewById(R.id.button1);
//new CreateUser().execute();
//sub.setOnClickListener(this);
//nm=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
//nm.cancel(uniqueId);
DefaultHttpClient httpClient = new DefaultHttpClient();
String url = "http://54.228.199.162/api/campaigns";
try {
String res;
HttpGet httpget = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpget);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8000);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
res = sb.toString();
Log.d("um1", res);
JSONArray jsonArray = new JSONArray(res);
//campaign.setText(res);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String id = jsonObject.getString(TAG_ID);
String utfid = URLDecoder.decode(id, "UTF-8");
Constant.idusr = utfid;
//String name = jsonObject.getString(TAG_NAME);
// String utfname = URLDecoder.decode(name, "UTF-8");
String utfname = URLDecoder.decode(jsonObject.getString(TAG_NAME), "UTF-8");
Log.d("IDDDDDDD", id);
Log.d("Nameeeeeee", utfname);
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, utfid);
map.put(TAG_NAME, utfname);
//Object contactList;
contactList.add(map);
}
HttpResponse httpresponse = httpClient.execute(httpget);
int responsecode = httpresponse.getStatusLine().getStatusCode();
Log.d("responsenummmm", "um11111"+responsecode);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
};
//this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, contactList));
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_NAME,TAG_ID}, new int[] {
R.id.label, R.id.id});
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String idof = ((TextView) view.findViewById(R.id.id)).getText().toString();
String nameof = ((TextView) view.findViewById(R.id.label)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), DonateActivity.class);
in.putExtra(TAG_NAME, nameof);
in.putExtra(TAG_ID, idof);
startActivity(in);
}
});
}
}
Here is the xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:paddingBottom="10dip"
android:paddingLeft="10dip"
android:paddingTop="10dip" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="#drawable/firstscreenimage" />
<TextView
android:id="#+id/id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/relativeLayout1"
android:text="bd" />
<TextView
android:id="#+id/label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/id"
android:text="bd"
android:textColor="#C20000"
android:textSize="14sp"
android:textStyle="bold" />
</LinearLayout>
Here is my problem:
But the logo should be the first one not with every list item. Please help me.
Please remove ImageView and write it out of the linear layout which you used. as you said that only once you need this imageview. beside this what you can do is make a custom adapter and custom listview and fix it that only for position index 0 you need to show imageview.
Add your logo as a header view to the list. Try following-
LayoutInflater inflater = getLayoutInflater();
ViewGroup header = (ViewGroup)inflater.inflate(R.layout.header, myListView, false);
myListView.addHeaderView(header, null, false);
In the header layout you can create an imageView for your logo.
this is another way :
<?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" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="#drawable/ic_plusone_medium_off_client" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
On your get View method of custom adapter do like this
Suppose your logo is assigned on some ImageView and your ImageView id is img
on xml by default put Visiblity of Logo to GONE
so you can make it's Visiblity VISIBLE at run time as below, for the first position of list view, it's very simple
if(position==0){
img.setVisiblity(View.VISIBLE);
}
try this code :
//Create a class extend View example MyHeader
MyHeader header = new MyHeader();
listview.addHeader(header );
This may help you....
Create another layout(i.e xml file) and insert image view first and then list view , now in on create method call this layout and by using hash map bind the above explained xml/layout file.
Note : Don't forget to remove image view from above explained layout.
Have a look at the SO link below, lots of nice links to implement listview Headers.
How to add Header to List View In Android
Try in this manner:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:paddingBottom="10dip"
android:paddingLeft="10dip"
android:paddingTop="10dip" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:visibility="gone"
android:src="#drawable/firstscreenimage" />
<TextView
android:id="#+id/id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/relativeLayout1"
android:text="bd" />
<TextView
android:id="#+id/label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/id"
android:text="bd"
android:textColor="#C20000"
android:textSize="14sp"
android:textStyle="bold" />
</LinearLayout>
After that in your code find the position of first list view in this manner:
if(****find the list*** position==0){
img.setVisiblity(View.VISIBLE);
}
I have been messing with this code for about a day and I can't seem to figure out what's going wrong. I'm trying to receive some JSON and then dynamically create Views from the response. I'll post the code and then explain the problem.
AsyncTask
private static final String TAG_SUCCESS = "success";
private static final String TAG_QUESTIONS = "questions";
private static final String TAG_NAME = "display_name";
private static final String TAG_FIELD = "field_type";
private static final String TAG_VALUE = "option_value";
private String r = "Radio";
class LoadAllQuestions extends AsyncTask<String, String, MyResult> {
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
JSONArray questions = null;
MyResult theResult = null;
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading questions. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected MyResult doInBackground(String... args) {
// getting JSON string from URL
companyName = cn.getText().toString();
projectName = pn.getText().toString();
String componentName = (String) ab.getSelectedTab().getText();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("company", companyName));
nameValuePairs.add(new BasicNameValuePair("project", projectName));
nameValuePairs.add(new BasicNameValuePair("component",
componentName));
JSONObject json = jParser.makeHttpRequest(url, "POST",
nameValuePairs);
// Check your log cat for JSON response
Log.d("All Questions: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.v("RESPONSE", "Success!");
// products found: getting Array of Questions
questions = json.getJSONArray(TAG_QUESTIONS);
// looping through All Questions
for (int i = 0; i < questions.length(); i++) {
JSONObject c = questions.getJSONObject(i);
// Storing each JSON item in variable
String name = c.getString(TAG_NAME);
String field = c.getString(TAG_FIELD);
String value = c.getString(TAG_VALUE);
if (r.equals(field)) {
Log.v("RESPONSE", "oh look a radio button");
theResult = new MyResult();
theResult.setType(1);
theResult.setName(name);
theResult.setField(field);
theResult.setValue(value);
} else if (et.equals(field)){
Log.v("RESPONSE", "just another EditText");
theResult = new MyResult();
theResult.setType(2);
theResult.setName(name);
theResult.setField(field);
theResult.setValue(value);
} else {
}
}
} else {
// no products found
Log.v("ERROR", "No JSON for you!");
}
} catch (JSONException e) {
e.printStackTrace();
}
return theResult;
}
protected void onPostExecute(MyResult theResult) {
// dismiss the dialog
pDialog.dismiss();
// if the answer should be a radio button, inflate it
if (theResult.getType() == 1) {
Log.v("RESPONSE", "About to create a radio button");
// find
LinearLayout content = (LinearLayout) view
.findViewById(R.id.genA_layout);
// create
TextView tv = new TextView(getActivity());
RadioGroup rg = new RadioGroup(getActivity());
rg.setOrientation(RadioGroup.HORIZONTAL);
RadioButton rb = new RadioButton(getActivity());
RadioButton rb2 = new RadioButton(getActivity());
LinearLayout ll = new LinearLayout(getActivity());
// set
rb.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
rb2.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
ll.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
rb.setText(theResult.getValue());
Log.v("RESPONSE", theResult.getValue());
rb2.setText(theResult.getValue());
tv.setText(theResult.getName());
Log.v("RESPONSE", theResult.getName());
ll.setOrientation(LinearLayout.HORIZONTAL);
// add
rg.addView(rb);
rg.addView(rb2);
ll.addView(tv);
ll.addView(rg);
content.addView(ll);
}
// else inflate the view as an EditText field
else if (theResult.getType() == 2) {
Log.v("RESPONSE", "About to create an EditText");
// find
LinearLayout content = (LinearLayout) view
.findViewById(R.id.genA_layout);
// create
TextView tv = new TextView(getActivity());
EditText et = new EditText(getActivity());
LinearLayout ll1 = new LinearLayout(getActivity());
// set
tv.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
et.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
ll1.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
tv.setText(theResult.getName());
Log.v("RESPONSE", theResult.getName());
ll1.setOrientation(LinearLayout.HORIZONTAL);
// add
ll1.addView(tv);
ll1.addView(et);
content.addView(ll1);
}
// find
LinearLayout loader = (LinearLayout) view
.findViewById(R.id.loader_layout);
Button save = (Button) view
.findViewById(R.id.generalAssets_save_button_ID);
// set
loader.setVisibility(View.GONE);
save.setVisibility(View.VISIBLE);
};
}
XML
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gen_assets"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/twoglobe_line"
android:gravity="center"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/genA_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="10dp"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/loader_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:gravity="center"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/info_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:gravity="center"
android:orientation="horizontal" >
<TextView
android:id="#+id/company_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/company_name" />
<EditText
android:id="#+id/company_input"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" />
</LinearLayout>
<LinearLayout
android:id="#+id/info_layout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="10dp"
android:gravity="center"
android:orientation="horizontal" >
<TextView
android:id="#+id/project_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/project_name" />
<EditText
android:id="#+id/project_input"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" />
</LinearLayout>
<Button
android:id="#+id/generalAssets_load_button_ID"
style="?android:attr/borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/load" />
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawSelectorOnTop="false" >
</ListView>
</LinearLayout>
<Button
android:id="#+id/generalAssets_save_button_ID"
style="?android:attr/borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/save"
android:visibility="gone" />
</LinearLayout>
</ScrollView>
logcat
06-03 16:04:51.948: E/json data(4103): json result {"questions":[{"display_name":"Store #","field_type":"Text Field","option_value":""},{"display_name":"Address","field_type":"Text Field","option_value":""},{"display_name":"Type of Business","field_type":"Drop Down Menu","option_value":"Education\r\nHealth\r\nComputers\r\nFood\r\nRetail\r\nOther"},{"display_name":"Is this business good?","field_type":"Radio","option_value":"Yes\r\nNo"},{"display_name":"Are they nice people?","field_type":"Check Box","option_value":"Yes\r\nNo"}],"success":1}
06-03 16:04:51.958: D/All Questions:(4103): {"success":1,"questions":[{"option_value":"","field_type":"Text Field","display_name":"Store #"},{"option_value":"","field_type":"Text Field","display_name":"Address"},{"option_value":"Education\r\nHealth\r\nComputers\r\nFood\r\nRetail\r\nOther","field_type":"Drop Down Menu","display_name":"Type of Business"},{"option_value":"Yes\r\nNo","field_type":"Radio","display_name":"Is this business good?"},{"option_value":"Yes\r\nNo","field_type":"Check Box","display_name":"Are they nice people?"}]}
06-03 16:04:51.958: V/RESPONSE(4103): Success!
06-03 16:04:51.958: V/RESPONSE(4103): just another EditText
06-03 16:04:51.958: V/RESPONSE(4103): just another EditText
06-03 16:04:51.958: V/RESPONSE(4103): oh look a radio button
Now the problem is none of the Views are being created. As you can see from the logcat posts the application pulls the JSON response and then it identifies them. However it never makes it to the point in onPostExecute() where it creates the Views. After making the changes #dmon suggested I have to think that my result I'm storing is going out of scope. Otherwise when I called my theResult.getType() method it would have a value. Right now it obviously doesn't.
Even though I think I know the problem, I cannot figure out why. Any help or insight is appreciated.
edited to show changes
"Why is it always an Edit Text?" - the reason is your comparison:
if (field == r) //where r is "Radio"
String comparisons in java are done with .equals(), so you want something like this:
if ("Radio".equals(field)) { ... }
"Why doesn't it add them?" - the reason is probably your layout. ScrollViews are vertical. The child is actually a horizontal LL:
<LinearLayout
android:id="#+id/genA_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="10dp"
android:orientation="horizontal" >
Then the first child of that has a width of "match_parent". Not sure how you can add any siblings to that that would be visible... So you either want your ScrollView to be a HorizontalScrollView or you want your LL to actually be vertical...
Edit:
Something else wrong that I noticed, you are using only one "result" variable:
MyResult theResult = null;
Which you keep overwriting every time you find a new element. You need to keep an List or array of results. onPostExecute() will only run once for the whole Async operation.