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);
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 tried to implement multiple gridView within a scrollview so that all girdview has only one scrollbar.
I used two gridView.
My layout is like that:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<com.example.ExpandableHeightGridView
android:id="#+id/gridView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:horizontalSpacing="2dp"
android:isScrollContainer="false"
android:numColumns="2"
android:stretchMode="columnWidth"
android:verticalSpacing="20dp" />
<com.example.ExpandableHeightGridView
android:id="#+id/gridView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:horizontalSpacing="2dp"
android:isScrollContainer="false"
android:numColumns="1"
android:stretchMode="columnWidth"
android:verticalSpacing="20dp" />
</LinearLayout>
</ScrollView>
I used This like for "ExpandableHeightGridView"
and in main activity i used this:
final ExpandableHeightGridView gView1 = new ExpandableHeightGridView(this);
gView1.setNumColumns(2);
ArrayList<HashMap<String, String>> list_of_wordmeanings = new ArrayList<HashMap<String, String>>();
Cursor mCursor = mDbHelper.getWord(value_of_category_id);
for (int i = 0; i < mCursor.getCount(); i++)
{
mCursor.moveToPosition(i);
HashMap<String, String> hm = new HashMap<String, String>();
String column1data = mCursor.getString(0).toString();
String column2data = mCursor.getString(1).toString();
String column3data = mCursor.getString(2).toString();
hm.put("key_word",column1data);
hm.put("key_meaning",column2data);
hm.put("key_translitaration",column3data);
list_of_wordmeanings.add(hm);
}
// Keys used in Hashmap
String[] from = { "key_word","key_meaning","key_translitaration" };
int[] to = { R.id.txt1,R.id.txt2,R.id.txt3}; // Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), list_of_wordmeanings, R.layout.grid_layout, from, to);
// Setting the adapter to the listView
gView1.setAdapter(adapter);
gView1.setExpanded(true);
gView1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
// TODO Auto-generated method stub
HashMap<String, String> hash = new HashMap<String, String>();
hash=(HashMap<String, String>) gView1.getItemAtPosition(position);
String english_word=hash.get("key_word");
String native_word=hash.get("key_meaning");
// Show Alert
Toast.makeText(getApplicationContext(),
" gridViewValue : "+native_word , Toast.LENGTH_LONG)
.show();
}
});
It doesn't work properly.
In GridView2, you restricted with Number of Columns as 1. Check it.
The purpose of GridView is to implement multiple columns.
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();
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 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.