Handeling adapters from list view to single item view class - java
I have a class viewroom.java, to list all the rooms' title from database, as follows:
package com.iwantnew.www;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.TargetApi;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
//import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public class viewroom extends ListActivity {
// url to make request
private static String url = "http://10.0.2.2/iWant/src/android_view_all_room.php";
// JSON Node names
private static final String TAG_ROOM = "room";
// private static final String TAG_SUCCESS = "success";
private static final String TAG_ID = "id";
private static final String TAG_LOCATION = "location";
private static final String TAG_TITLE = "title";
private static final String TAG_QUANTITY = "quantity";
private static final String TAG_PRICE = "price";
private static final String TAG_CONTACT = "contact";
private static final String TAG_AREA = "area";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_ADDRESS = "address";
// contacts JSONArray
JSONArray room = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_room);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
// Hashmap for ListView
ArrayList<HashMap<String, String>> roomList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url, "GET", params);
try {
// Getting Array of Contacts
room = json.getJSONArray(TAG_ROOM);
// looping through All Contacts
for(int i = 0; i < room.length(); i++){
JSONObject c = room.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String location = c.getString(TAG_LOCATION);
String quantity = c.getString(TAG_QUANTITY);
String address = c.getString(TAG_ADDRESS);
String price = c.getString(TAG_PRICE);
String contact = c.getString(TAG_CONTACT);
String area = c.getString(TAG_AREA);
String description = c.getString(TAG_DESCRIPTION);
String title = c.getString(TAG_TITLE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_LOCATION, location);
map.put(TAG_QUANTITY, quantity);
map.put(TAG_ADDRESS, address);
map.put(TAG_PRICE, price);
map.put(TAG_CONTACT, contact);
map.put(TAG_AREA, area);
map.put(TAG_DESCRIPTION, description);
map.put(TAG_TITLE, title);
// adding HashList to ArrayList
roomList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, roomList,
R.layout.list_room,
new String[] { TAG_TITLE, TAG_LOCATION, TAG_PRICE }, new int[] {
R.id.title, R.id.location, R.id.price });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String title = ((TextView) view.findViewById(R.id.title)).getText().toString();
String location = ((TextView) view.findViewById(R.id.location)).getText().toString();
String price = ((TextView) view.findViewById(R.id.price)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleRoomActivity.class);
in.putExtra(TAG_TITLE, title);
in.putExtra(TAG_LOCATION, location);
in.putExtra(TAG_PRICE, price);
startActivity(in);
}
});
}
}
when one of those list item is clicked, details are shown in single Room Activity class. it
is as follows:
package com.iwantnew.www;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class SingleRoomActivity extends Activity {
private static final String TAG_TITLE = "title";
private static final String TAG_LOCATION = "location";
private static final String TAG_PRICE = "price";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.single_room);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String title = in.getStringExtra(TAG_TITLE);
String location = in.getStringExtra(TAG_LOCATION);
String price = in.getStringExtra(TAG_PRICE);
// Displaying all values on the screen
TextView lblTitle = (TextView) findViewById(R.id.title_label);
TextView lblLocation = (TextView) findViewById(R.id.location_label);
TextView lblPrice = (TextView) findViewById(R.id.price_label);
lblTitle.setText(title);
lblLocation.setText(location);
lblPrice.setText(price);
}
}
there remains a big gap between each items in view room activity class, when all details are shown in single room activity.
and when list adapter is modified to
ListAdapter adapter = new SimpleAdapter(this, roomList,
R.layout.list_room,
new String[] { TAG_TITLE }, new int[] {
R.id.title });
in view room activity, the gap vanishes but, single room activity does not show all the description.
in case you need my xml files:
view_room.xml
<?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:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<Button
android:id="#+id/searchBtn"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/slogan"
android:text="#string/Search" />
<EditText
android:id="#+id/searchArea"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignTop="#+id/searchBtn"
android:ems="10"
android:hint="#string/hint"
android:inputType="text" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/slogan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/searchArea"
android:layout_below="#+id/brand"
android:text="#string/slogan"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textStyle="italic"
android:typeface="normal" />
<TextView
android:id="#+id/brand"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="#string/iWant"
android:textSize="#dimen/iwant" />
<Button
android:id="#+id/postBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="26dp"
android:text="#string/post" />
<TextView
android:id="#+id/room_list_heading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/searchBtn"
android:text="#string/room_list_heading"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textStyle="italic"
android:typeface="normal" />
<ListView
android:id="#android:id/list"
android:layout_below="#+id/room_list_heading"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
single room.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<!-- Name Label -->
<TextView android:id="#+id/title_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="25dip"
android:textStyle="bold"
android:paddingTop="10dip"
android:paddingBottom="10dip"
android:textColor="#43bd00"/>
<!-- Description Label -->
<TextView android:id="#+id/quantity_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/location_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textStyle="bold"/>
<TextView android:id="#+id/price_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="25dip"
android:textStyle="bold"
android:paddingTop="10dip"
android:paddingBottom="10dip"
android:textColor="#43bd00"/>
<TextView android:id="#+id/contact_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/description_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textStyle="bold"/>
<TextView android:id="#+id/area_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="25dip"
android:textStyle="bold"
android:paddingTop="10dip"
android:paddingBottom="10dip"
android:textColor="#43bd00"/>
<TextView android:id="#+id/address_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
list_room.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="horizontal">
<!-- Name Label -->
<TextView
android:id="#+id/title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#43bd00"
android:textSize="16sp"
android:textStyle="bold"
android:paddingTop="6dip"
android:paddingBottom="2dip" />
<!-- Description label -->
<TextView
android:id="#+id/location"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip">
</TextView>
<TextView
android:id="#+id/quantity"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip">
</TextView>
<TextView
android:id="#+id/price"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip">
</TextView>
<TextView
android:id="#+id/contact"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip">
</TextView>
<TextView
android:id="#+id/area"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip">
</TextView>
<TextView
android:id="#+id/description"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip">
</TextView>
<TextView
android:id="#+id/address"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip">
</TextView>
</LinearLayout>
I want to vanish gap in the first picture and still get the second picture as it is.
Related
Unexpected behaviour with custom ListView adapter
So I've got a listView and each item basically displays 3 TextView-s one of the TextView-s represents username and if the username is equal to the logged user the item shall be highlighted(see code) import android.content.Context; import android.graphics.Color; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.List; public class ListAdapter extends ArrayAdapter<HallOfFame.User> { private int resourceLayout; private Context mContext; public ListAdapter(Context context, int resource, List<HallOfFame.User> items) { super(context, resource, items); this.resourceLayout = resource; this.mContext = context; } #Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { LayoutInflater vi; vi = LayoutInflater.from(mContext); v = vi.inflate(resourceLayout, null); } HallOfFame.User user = getItem(position); if (user != null) { TextView rankText = v.findViewById(R.id.rank); TextView usernameText = v.findViewById(R.id.username); TextView scoreText = v.findViewById(R.id.score); rankText.setText(Integer.toString(user.rank)); usernameText.setText(user.username); scoreText.setText(Integer.toString(user.overall)); if(Utils.USERNAME.equals(user.username)){ usernameText.setTextColor(Color.RED); } } return v; } } In this example only MikiThenics should be highlighted. Adding else after if(Utils.USERNAME.eq...) will stop the other usernames from being highlighted but there's still this weird shift with the number on the right. And the items that are "not working" aren't always the same. This is how the HallOfFame.User looks: public class User{ public String username; public int pullups=0,pushups,dips,handstandpushups,plank,pistolsquats,muscleups; public int overall; public int rank = 0; public User(String data,int i){ try { JSONObject jsonObject = new JSONObject(data); username = jsonObject.getString(Utils.S_USERNAME); pullups = jsonObject.getInt(Utils.S_PULL_UPS); pushups = jsonObject.getInt(Utils.S_PUSH_UPS); dips = jsonObject.getInt(Utils.S_DIPS); handstandpushups = jsonObject.getInt(Utils.S_HANDSTAND_PUSHUPS); plank = jsonObject.getInt(Utils.S_PLANK); pistolsquats = jsonObject.getInt(Utils.S_PISTOL_SQUATS); muscleups = jsonObject.getInt(Utils.S_MUSCLE_UPS); overall = pullups+pushups+dips+handstandpushups+pistolsquats+muscleups+plank/60; rank = i; if(username.equals(Utils.USERNAME)) yourPosition = i; }catch (Exception e){ } } } This is the example of the JSON I'm using String tmp = "[{\"username\":\"MikiThenics\",\"pullups\":\"25\",\"pushups\":\"70\",\"dips\":\"30\",\"handstandpushups\":\"16\",\"muscleups\":\"8\",\"pistolsquats\":\"1\",\"plank\":\"360\"},{\"username\":\"user01\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user02\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user0\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user1\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user2\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user3\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user4\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user5\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user6\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user7\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user8\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user9\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user10\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user11\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user12\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user13\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user14\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user15\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user16\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user17\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user18\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user19\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user20\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user21\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user22\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user23\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user24\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user25\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user26\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user27\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user28\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user29\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user30\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user31\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user32\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user33\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user34\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user35\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user36\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user37\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user38\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user39\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user40\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user41\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user42\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user43\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user44\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user45\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user46\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user47\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user48\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user49\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user50\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user51\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user52\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user53\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user54\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user55\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user56\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user57\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user58\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user59\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user60\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user61\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user62\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user63\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user64\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user65\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user66\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user67\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user68\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user69\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user70\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user71\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user72\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user73\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user74\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user75\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user76\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"},{\"username\":\"user77\",\"pullups\":\"0\",\"pushups\":\"0\",\"dips\":\"0\",\"handstandpushups\":\"0\",\"muscleups\":\"0\",\"pistolsquats\":\"0\",\"plank\":\"0\"}]"; The problem is caused by the username. Since setting username in User to fixed String solves the problem. Even though I'm using fixed string as JSON the "not working items" aren't the same when restarting the activity.
It's a XML issue. You can try with this. <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_height="wrap_content" android:orientation="vertical" android:layout_width="match_parent"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" android:paddingTop="10dp" android:paddingBottom="10dp" > <TextView android:id="#+id/rank" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:text="RANK" android:textColor="#000000" android:textColorHighlight="#000000" android:textColorHint="#000000" android:textColorLink="#000000" android:textSize="16sp" android:layout_alignParentStart="true" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <TextView android:id="#+id/username" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="12dp" android:text="Name" android:textColor="#000000" android:textColorHighlight="#000000" android:textColorHint="#000000" android:textColorLink="#000000" android:textSize="16sp" android:layout_toEndOf="#+id/rank" /> <TextView android:id="#+id/score" android:layout_width="50dp" android:layout_height="wrap_content" android:layout_marginEnd="8dp" android:text="SCORE" android:textColor="#000000" android:textColorHighlight="#000000" android:textColorHint="#000000" android:textColorLink="#000000" android:textSize="16sp" android:layout_alignParentEnd="true" /> </RelativeLayout> </androidx.constraintlayout.widget.ConstraintLayout>
You can add an boolean into your if statement that at first it is true and when tries to highlited the username's text , set the boolean false if(Utils.USERNAME.equals(user.username) && boolean){ usernameText.setTextColor(Color.RED); }
How to handle NULL results from JSON when I click on list view row?
Very little experience when it comes to Java. My app pulls data from an API to a list view just fine. Once clicked on the list view I want to display more details. My code is in different files and I can't figure out how handle null results when I set my text view text. Right now it is giving me a few errors. Thank you in advanced. I've tried debugging and my own research to no avail for over a day. My error was: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference. MainActivity.java: public void showMemberDetailsScreen(int _id) { mMembersListScreen.setVisibility(View.GONE); mMemberDetailsScreen.setVisibility(View.VISIBLE); if (NetworkUtils.isConnected(this)) { GetDetailsTask task = new GetDetailsTask(this); task.execute(_id); } else { Log.i(TAG, "onCreate: NOT CONNECTED"); } } /** * Populate the member details screen with data. * * #param _name * #param _birthday * #param _gender * #param _twitterId * #param _numCommittees * #param _numRoles */ public void populateMemberDetailsScreen(String _name, String _birthday, String _gender, String _twitterId, String _numCommittees, String _numRoles) { TextView tv = (TextView)mMembersListScreen.findViewById(R.id.text_name); tv.setText(_name); tv = (TextView)mMembersListScreen.findViewById(R.id.text_birthday); tv.setText(_birthday); tv = (TextView)mMembersListScreen.findViewById(R.id.text_gender); tv.setText(_gender); tv = (TextView)mMembersListScreen.findViewById(R.id.text_twitter_id); tv.setText(_twitterId); tv = (TextView)mMembersListScreen.findViewById(R.id.text_num_committees); tv.setText(_numCommittees); tv = (TextView)mMembersListScreen.findViewById(R.id.text_num_roles); tv.setText(_numRoles); } OnItemClickListener mItemClickListener = new OnItemClickListener() { #Override public void onItemClick(AdapterView<?> _parent, View _view, int _position, long _id) { // TODO: Show the members detail screen Log.i(TAG, "onItemClick: RAN"); showMemberDetailsScreen(_position); Log.i(TAG, "onItemClick: POSITION = " + _position); } }; GetDetailsTask.java: private static final String NAME = "name"; private static final String BIRTHDAY = "birthday"; private static final String GENDER = "gender"; private static final String TWITTER_ID = "twitter_id"; private static final String NUM_COMMITTEES = "num_committees"; private static final String NUM_ROLES = "num_roles"; private MainActivity mActivity; public GetDetailsTask(MainActivity _activity) { mActivity = _activity; } #Override protected HashMap<String, String> doInBackground(Integer... _params) { // Add member ID to the end of the URL String data = NetworkUtils.getNetworkData(API_URL + _params[0]); HashMap<String, String> retValues = new HashMap<String, String>(); try { JSONObject response = new JSONObject(data); String name = response.optString("name"); retValues.put(NAME, name); String birthday = response.optString("birthday"); retValues.put(BIRTHDAY, birthday); String gender = response.optString("gender_label"); retValues.put(GENDER, gender); String twitterId = response.optString("twitterid"); retValues.put(TWITTER_ID, twitterId); if (response.has("committeeassignments")) { JSONArray committeeArray = response.optJSONArray("committeeassignments"); int numCommittees = committeeArray.length(); retValues.put(NUM_COMMITTEES, "" + numCommittees); Log.i(TAG, "doInBackground: NUM COMMITTESS = " + numCommittees); } else { retValues.put(NUM_COMMITTEES, "" + 0); } if (response.has("roles")){ JSONArray rolesArray = response.optJSONArray("roles"); int numRoles = rolesArray.length(); retValues.put(NUM_ROLES, "" + numRoles); } else { retValues.put(NUM_ROLES, "" + 0); } } catch(JSONException e) { e.printStackTrace(); } return retValues; } #Override protected void onPostExecute(HashMap<String, String> _result) { super.onPostExecute(_result); if (_result != null) { String name = _result.get(NAME); String birthday = _result.get(BIRTHDAY); String gender = _result.get(GENDER); String twitterId = _result.get(TWITTER_ID); String numCommittees = _result.get(NUM_COMMITTEES); String numRoles = _result.get(NUM_ROLES); mActivity.populateMemberDetailsScreen(name, birthday, gender, twitterId, numCommittees, numRoles); } } activity_main.xml: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:id="#+id/members_list_screen" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:visibility="gone" > <ListView android:id="#+id/members_list" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout> <LinearLayout android:id="#+id/member_details_screen" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:visibility="gone" > <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="#string/name" /> <TextView android:id="#+id/text_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" /> </LinearLayout> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="#string/birthday" /> <TextView android:id="#+id/text_birthday" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" /> </LinearLayout> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="#string/gender" /> <TextView android:id="#+id/text_gender" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" /> </LinearLayout> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="#string/twitter_id" /> <TextView android:id="#+id/text_twitter_id" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" /> </LinearLayout> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="#string/num_committees" /> <TextView android:id="#+id/text_num_committees" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" /> </LinearLayout> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="#string/name" /> <TextView android:id="#+id/text_num_roles" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" /> </LinearLayout> </LinearLayout>
You are trying to show your details screen but in your method you are finding view by id under your mMembersListScreen when you should use mMemberDetailsScreen. Try this: public void populateMemberDetailsScreen(String _name, String _birthday, String _gender, String _twitterId, String _numCommittees, String _numRoles) { TextView tv = (TextView) mMemberDetailsScreen.findViewById(R.id.text_name); tv.setText(_name); tv = (TextView) mMemberDetailsScreen.findViewById(R.id.text_birthday); tv.setText(_birthday); tv = (TextView) mMemberDetailsScreen.findViewById(R.id.text_gender); tv.setText(_gender); tv = (TextView) mMemberDetailsScreen.findViewById(R.id.text_twitter_id); tv.setText(_twitterId); tv = (TextView) mMemberDetailsScreen.findViewById(R.id.text_num_committees); tv.setText(_numCommittees); tv = (TextView) mMemberDetailsScreen.findViewById(R.id.text_num_roles); tv.setText(_numRoles); }
where to put android.support.v4.widget.SwipeRefreshLayout and how to implement it?
just wanna ask where to put the android.support.v4.widget.SwipeRefreshLayout on my codes? I'm confused if it should be on my activity_main.xml or in my list_item.xml file.. Here is my activity_main.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="fill_parent" android:orientation="vertical" > <ListView android:id="#+android:id/list" android:layout_width="fill_parent" android:layout_height="wrap_content"/> </LinearLayout> And This is my List_item.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="10dp" android:paddingLeft="10dp" android:paddingRight="10dp"> <TextView android:id="#+id/datetime" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingBottom="2dip" android:paddingTop="6dip" android:textColor="#43bd00" android:textSize="16sp" android:textStyle="bold" android:layout_weight="1" /> <TextView android:id="#+id/qname" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingBottom="2dip" android:textColor="#acacac" android:layout_weight="1" /> <TextView android:id="#+id/qagent" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingBottom="2dip" android:textColor="#acacac" android:layout_weight="1" /> <TextView android:id="#+id/qevent" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingBottom="2dip" android:textColor="#acacac" android:layout_weight="1" /> <TextView android:id="#+id/info1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingBottom="2dip" android:textColor="#acacac" android:layout_weight="1" /> <TextView android:id="#+id/info2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingBottom="2dip" android:textColor="#acacac" android:layout_weight="1" /> <TextView android:id="#+id/info3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingBottom="2dip" android:textColor="#acacac" android:layout_weight="1" /> </LinearLayout> I Found some sample codes on the internet where they put it on the main xml but some samples also put it on the list xml.. This is my Main activity : import java.util.ArrayList; import java.util.HashMap; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Fragment; import android.app.ListActivity; import android.app.ProgressDialog; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; public class MainActivity extends ListActivity { private ProgressDialog pDialog; private static String IPaddress = "http://192.168.1.110/"; // URL to get contacts JSON private static String url = IPaddress + "Projects/GetUsers.php"; private static final String TAG_QUEUE = "queue"; private static final String TAG_DATETIME = "datetime"; private static final String TAG_NAME = "qname"; private static final String TAG_AGENT = "qagent"; private static final String TAG_EVENT = "qevent"; private static final String TAG_INFO1 = "info1"; private static final String TAG_INFO2 = "info2"; private static final String TAG_INFO3 = "info3"; // contacts JSONArray JSONArray queue = null; // Hashmap for ListView ArrayList<HashMap<String, String>>queueList; #Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); queueList = new ArrayList<HashMap<String, String>>(); // ListView lv = getListView(); // Calling async task to get json new GetEventCounter().execute(); } /** * Async task class to get json by making HTTP call * */ private class GetEventCounter extends AsyncTask<Void, Void, Void> { #Override protected void onPreExecute() { super.onPreExecute(); // Showing progress dialog pDialog = new ProgressDialog(MainActivity2.this); pDialog.setMessage("Please wait..."); pDialog.setCancelable(false); pDialog.show(); } #Override protected Void doInBackground(Void... arg0) { // Creating service handler class instance ServiceHandler sh = new ServiceHandler(); // Making a request to url and getting response String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET); Log.d("Response: ", "> " + jsonStr); if (jsonStr != null) { try { JSONObject jsonObj = new JSONObject(jsonStr); queue = jsonObj.getJSONArray(TAG_QUEUE); for (int i = 0; i < queue.length(); i++) { JSONObject c = queue.getJSONObject(i); String datetime = String.format("%s : %s", TAG_DATETIME, c.getString(TAG_DATETIME)); String qname = String.format("%s : %s", TAG_NAME, c.getString(TAG_NAME)); String qagent = String.format("%s : %s", TAG_AGENT, c.getString(TAG_AGENT)); String qevent = String.format("%s : %s", TAG_EVENT, c.getString(TAG_EVENT)); String info1 = String.format("%s : %s", TAG_INFO1, c.getString(TAG_INFO1)); String info2 = String.format("%s : %s", TAG_INFO2, c.getString(TAG_INFO2)); String info3 = String.format("%s : %s", TAG_INFO3, c.getString(TAG_INFO3)); HashMap<String, String> event = new HashMap<String, String>(); event.put(TAG_DATETIME, datetime); event.put(TAG_NAME, qname); event.put(TAG_AGENT, qagent); event.put(TAG_EVENT, qevent); event.put(TAG_INFO1, info1); event.put(TAG_INFO2, info2); event.put(TAG_INFO3, info3); queueList.add(event); } } catch (JSONException e) { e.printStackTrace(); } } else { Log.e("ServiceHandler", "Couldn't get any data from the url"); } return null; } #Override protected void onPostExecute(Void result) { super.onPostExecute(result); // Dismiss the progress dialog if (pDialog.isShowing()) pDialog.dismiss(); /** * Updating parsed JSON data into ListView * */ ListAdapter adapter = new SimpleAdapter( MainActivity2.this, queueList, R.layout.list_item, new String[] { TAG_DATETIME, TAG_NAME, TAG_AGENT, TAG_EVENT, TAG_INFO1, TAG_INFO2, TAG_INFO3}, new int[] { R.id.datetime, R.id.qname, R.id.qagent, R.id.qevent, R.id.info1, R.id.info2, R.id.info3 }); setListAdapter(adapter); } } protected Fragment getSampleFragment() { // TODO Auto-generated method stub return null; } } This will be the output that i want to have an SwipeRefresh effect.. Those output came from MySQL Database : This samples caused my confusion <android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="#+id/swype" android:layout_width="match_parent" android:layout_height="match_parent"> <ListView android:id="#+id/list" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </android.support.v4.widget.SwipeRefreshLayout> And : <?xml version="1.0" encoding="utf-8"?> <android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="#+id/swype" android:layout_width="match_parent" android:layout_height="match_parent"> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:id="#+id/serial" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="25dp" android:layout_margin="5dp" android:layout_alignParentLeft="true" android:textSize="20dp" android:textStyle="bold" /> <TextView android:id="#+id/title" android:layout_toRightOf="#id/serial" android:layout_centerVertical="true" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="bold" android:paddingLeft="20dp" android:textSize="18dp" /> </RelativeLayout> </android.support.v4.widget.SwipeRefreshLayout> Thanks!
To add the swipe to refresh widget to an existing app, add SwipeRefreshLayout as the parent of a single ListView or GridView. Remember that SwipeRefreshLayout only supports a single ListView or GridView child. - Add the SwipeRefreshLayout Widget So, your activity_main.xml should be like this: <?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="fill_parent" android:orientation="vertical" > <android.support.v4.widget.SwipeRefreshLayout android:id="#+id/swipeLayout" android:layout_width="match_parent" android:layout_height="match_parent"> <ListView android:id="#+android:id/list" android:layout_width="match_parent" android:layout_height="match_parent"/> </android.support.v4.widget.SwipeRefreshLayout </LinearLayout> Implementation: public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener{ private SwipeRefreshLayout swipeRefreshLayout #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeLayout); swipeRefreshLayout.setOnRefreshListener(this); //to change the color of the refresh indictor swipeRefreshLayout.setColorScheme(getResources().getColor(R.color.yourcolor), getResources().getColor(R.color.yourcolor), getResources().getColor(R.color.yourcolor), getResources().getColor(R.color.yourcolor)); } #Override public void onRefresh() { //do something here //setRefreshing(false) will hide the indicator swipeRefreshLayout.setRefreshing(false); } }
It should wrap around the listview, something like this: <android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="#+id/swiperefresh" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingTop="8dp"> <android.widget.ListView android:id="#android:id/list" android:layout_width="match_parent" android:layout_height="wrap_content"> </android.widget.ListView> </android.support.v4.widget.SwipeRefreshLayout> If you're using Android Studio, you can look at a Swiperefresh sample: File\New\Import Sample\ then search for "swipe..." In your java code, you initialize the SwipeRefresh object exactly how you would do a TextView, Button or anything else, except in your onResume(), you also want to put something like this: mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { #Override public void onRefresh() { initiateRefresh(); } }); and then inside initiateRefresh(), you do something like: AssignData2ListView(); mSwipeRefreshLayout.setRefreshing(false);
Set TextView text with a for loop so multiple lines show
So I have a for loop that I want to output a new line in a textview every single time it goes through. However, I am not sure if that is possible. I have TableLayout in there but it put the items vertically instead of horizontally. I thought about ListView but not sure how to set the text of it. Here is my code import android.app.Fragment; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import com.example.jamessingleton.chffrapi.com.examples.jamessingleton.chffrapi.data.Route; import org.joda.time.DateTime; import org.w3c.dom.Text; import java.io.IOException; import java.util.Map; import okhttp3.Request; import okhttp3.Response; /** * Created by James Singleton on 8/13/2016. */ public class WeeklyDrives extends Fragment implements APIRequestsUtil.APIRequestResponseListener { View myView; Map<String, Route> drives; private TextView driveNumber; private TextView driveDistance; private TextView driveTime; private TextView driveNumList; private TextView driveDistList; private TextView driveTimeList; #Nullable #Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { myView = inflater.inflate(R.layout.weekly_drives, container, false); APIRequestsUtil.setOnNetWorkListener(this); return myView; } private void populateView() { this.getActivity().runOnUiThread(new Runnable() { #Override public void run() { drives = APIRequestsUtil.getRoutes(); driveNumber = (TextView) myView.findViewById(R.id.Drive_Number); driveDistance = (TextView) myView.findViewById(R.id.Drive_Distance); driveTime = (TextView) myView.findViewById(R.id.Drive_Time); driveNumber.setText("Drive Num."); driveDistance.setText("Distance"); driveTime.setText("Time"); int driveNum = 0; for (Map.Entry drive : drives.entrySet()) { TableRow tr = new TableRow(getActivity()); Route route = (Route) drive.getValue(); tr.setId(driveNum++); //tr.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); DateTime startTime = new DateTime(route.getStart_time()); DateTime endTime = new DateTime(route.getEnd_time()); driveNumList = (TextView) myView.findViewById(R.id.Drive_Number_List); driveDistList = (TextView) myView.findViewById(R.id.Drive_Distance_List); driveTimeList = (TextView) myView.findViewById(R.id.Drive_Time_List); driveNumList.setText(driveNumList.getText().toString() + String.valueOf(driveNum) + System.getProperty("line.separator")); driveDistList.setText(driveDistList.getText().toString() + Float.parseFloat(route.getLen()) / 1000 + " km" + System.getProperty("line.separator")); driveTimeList.setText(driveTimeList.getText().toString() + ((endTime.getMillis() - startTime.getMillis())/ 1000)/60 + " min" + System.getProperty("line.separator")); } } }); } #Override public void onFailure(Request request, Throwable throwable) { } #Override public void onResponse(Response response) { populateView(); } } Here is my XML: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <!--Header aligned to top --> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="#+id/header" android:gravity="center" android:background="#FC9"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="#+id/Drive_Number" android:layout_margin="4dp" android:textSize="20sp" android:textColor="#000"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="#+id/Drive_Distance" android:layout_toRightOf="#+id/Drive_Number" android:layout_margin="4dp" android:textSize="20sp" android:textColor="#000"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="#+id/Drive_Time" android:layout_toRightOf="#+id/Drive_Distance" android:layout_margin="4dp" android:textSize="20sp" android:textColor="#000"/> </RelativeLayout> <ScrollView android:layout_width="fill_parent" android:layout_height="fill_parent" android:scrollbars="vertical" android:background="#005" android:layout_below="#+id/header" android:id="#+id/scrollableContents"> <!--<TableLayout--> <!--android:id="#+id/fragment1_tlayout"--> <!--android:layout_width="wrap_content"--> <!--android:layout_height="wrap_content"--> <!--android:stretchColumns="0,1">--> <!--</TableLayout>--> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="#+id/Drive_Number_List" android:layout_margin="4dp" android:textSize="20sp" android:textColor="#CCCCCC" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="#+id/Drive_Distance_List" android:layout_toRightOf="#+id/Drive_Number_List" android:layout_margin="4dp" android:textSize="20sp" android:textColor="#CCCCCC"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="#+id/Drive_Time_List" android:layout_toRightOf="#+id/Drive_Distance_List" android:layout_margin="4dp" android:textSize="20sp" android:textColor="#CCCCCC"/> </LinearLayout> </ScrollView> </RelativeLayout> drive.entrySet() output What is this:[2016-07-11--08-52-18=com.example.jamessingleton.chffrapi.com.examples.jamessingleton.chffrapi.data.Route#12a862, 2016-07-11--09-37-46=com.example.jamessingleton.chffrapi.com.examples.jamessingleton.chffrapi.data.Route#50bbdf3, 2016-07-11--18-54-22=com.example.jamessingleton.chffrapi.com.examples.jamessingleton.chffrapi.data.Route#6d21ab0, 2016-07-12--09-15-59=com.example.jamessingleton.chffrapi.com.examples.jamessingleton.chffrapi.data.Route#fb72d29, 2016-07-12--09-29-29=com.example.jamessingleton.chffrapi.com.examples.jamessingleton.chffrapi.data.Route#776e8ae, 2016-07-12--09-33-03=com.example.jamessingleton.chffrapi.com.examples.jamessingleton.chffrapi.data.Route#d1a464f, 2016-07-12--09-38-56=com.example.jamessingleton.chffrapi.com.examples.jamessingleton.chffrapi.data.Route#5b631dc, 2016-07-12--09-41-08=com.example.jamessingleton.chffrapi.com.examples.jamessingleton.chffrapi.data.Route#dec72e5, 2016-07-12--09-42-39=com.example.jamessingleton.chffrapi.com.examples.jamessingleton.chffrapi.data.Route#acce1ba, 2016-07-12--09-44-33=com.example.jamessingleton.chffrapi.com.examples.jamessingleton.chffrapi.data.Route#5def86b, 2016-07-12--09-49-31=com.example.jamessingleton.chffrapi.com.examples.jamessingleton.chffrapi.data.Route#d628fc8, 2016-07-12--09-54-06=com.example.jamessingleton.chffrapi.com.examples.jamessingleton.chffrapi.data.Route#7765861, 2016-07-12--19-04-34=com.example.jamessingleton.chffrapi.com.examples.jamessingleton.chffrapi.data.Route#8575f86, 2016-07-12--19-39-20=com.example.jamessingleton.chffrapi.com.examples.jamessingleton.chffrapi.data.Route#3f2b047, 2016-07-12--19-40-27=com.example.jamessingleton.chffrapi.com.examples.jamessingleton.chffrapi.data.Route#df4e074, 2016-07-12--19-41-28=com.example.jamessingleton.chffrapi.com.examples.jamessingleton.chffrapi.data.Route#b5f199d, 2016-07-13--08-45-17=com.example.jamessingleton.chffrapi.com.examples.jamessingleton.chffrapi.data.Route#db9ee12, 2016-07-13--09-01-32=com.example.jamessingleton.chffrapi.com.examples.jamessingleton.chffrapi.data.Route#2a009e3, 2016-07-13--15-02-04=com.example.jamessingleton.chffrapi.com.examples.jamessingleton.chffrapi.data.Route#9b98fe0, 2016-07-14--08-46-22=com.example.jamessingleton.chffrapi.com.examples.jamessingleton.chffrapi.data.Route#518b299, 2016-07-14--19-22-46=com.example.jamessingleton.chffrapi.com.examples.jamessingleton.chffrapi.data.Route#d44d95e, 2016-07-14--19-34-02=com.example.jamessingleton.chffrapi.com.examples.jamessingleton.chffrapi.data.Route#d3f613f, 2016-07-14--20-16-47=com.example.jamessingleton.chffrapi.com.examples.jamessingleton.chffrapi.data.Route#957ca0c, 2016-07-15--08-36-28=com.example.jamessingleton.chffrapi.com.examples.jamessingleton.chffrapi.data.Route#b38df55, 2016-07-15--09-52-32=com.example.jamessingleton.chffrapi.com.examples.jamessingleton.chffrapi.data.Route#c012d6a, 2016-07-15--12-09-57=com.example.jamessingleton.chffrapi.com.examples.jamessingleton.chffrapi.data.Route#252d25b, 2016-07-15--12-15-07=com.example.jamessingleton.chffrapi.com.examples.jamessingleton.chffrapi.data.Route#6bd7af8, 2016-07-15--15-36-10=com.example.jamessingleton.chffrapi.com.examples.jamessingleton.chffrapi.data.Route#df51bd1,
Add android:inputType="textMultiLine" to the TextView in the XML. And add data into TextView like this: driveNumList.setText(driveNumList.getText().toString() + String.valueOf(driveNum) + System.getProperty("line.separator")); And so on. Edit: you can use "\n" instead of System.getProperty("line.separator") for adding the new line character.
I would recommend a ListView for this type of thing so that it is automatically scrollable, uses View recycling to maintain efficiency, cleans up your code and organizes it into digestible segments. To use a ListView, you first need to add it to your main XML file. So that would become the following: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <!--Header aligned to top --> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="#+id/header" android:gravity="center" android:background="#FC9"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="#+id/Drive_Number" android:layout_margin="4dp" android:textSize="20sp" android:textColor="#000"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="#+id/Drive_Distance" android:layout_toRightOf="#+id/Drive_Number" android:layout_margin="4dp" android:textSize="20sp" android:textColor="#000"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="#+id/Drive_Time" android:layout_toRightOf="#+id/Drive_Distance" android:layout_margin="4dp" android:textSize="20sp" android:textColor="#000"/> </RelativeLayout> <RelativeLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:scrollbars="vertical" android:background="#005" android:layout_below="#+id/header" android:id="#+id/scrollableContents"> <ListView android:id="#+id/listView" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </RelativeLayout> </RelativeLayout> Following that, you need to create your ListView adapter class. It is what handles what each individual list item's data is (the thing inside your for-loop). Here is one that you might use, although you may have to make your own tweaks and import more of your own classes, add your package name to the top, etc. So create a new Java class called DriveListAdapter.java and place the following code into it: import android.app.Activity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.List; import java.util.HashMap; import java.util.Map; public class DriveListAdapter extends ArrayAdapter<Map.Entry> { private final Activity context; // you may need to change List to something else (whatever is returned from drives.entrySet()) private final List<Map.Entry> drives; // may also need to change List here (above comment) public DriveListAdapter(Activity context, List<Map.Entry> drives) { super(context, R.layout.drive_list_item, drives); this.context = context; this.drives = drives; } #Override public View getView(int position, View view, ViewGroup parent) { LayoutInflater inflater = context.getLayoutInflater(); View rowView = inflater.inflate(R.layout.drive_list_item, null, true); Map.Entry drive = this.drives.get(position); // position is the index of the drives.entrySet() array int driveNum = position + 1; // need to import your Route class Route route = (Route) drive.getValue(); // need to import your DateTime class DateTime startTime = new DateTime(route.getStart_time()); DateTime endTime = new DateTime(route.getEnd_time()); TextView driveNumList = (TextView) rowView.findViewById(R.id.Drive_Number_List); TextView driveDistList = (TextView) rowView.findViewById(R.id.Drive_Distance_List); TextView driveTimeList = (TextView) rowView.findViewById(R.id.Drive_Time_List); driveNumList.setText(String.valueOf(driveNum)); driveDistList.setText(Double.parseDouble(route.getLen()) / 1000 + " km"); driveTimeList.setText((endTime.getMillis() - startTime.getMillis())/ 1000 + " s"); return rowView; } } Then, create a new layout file, which will be what the individual list item looks like. This layout is rendered for each and every drive in the list. You can adjust this layout file so that everything is aligned properly. I gave an example of how to do that (create a layout file called drive_list_item.xml): <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="4dp" android:textSize="20sp" android:textColor="#CCCCCC" android:text="Medium Text" android:id="#+id/Drive_Number_List" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="4dp" android:textSize="20sp" android:textColor="#CCCCCC" android:text="Medium Text" android:id="#+id/Drive_Distance_List" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="4dp" android:textSize="20sp" android:textColor="#CCCCCC" android:text="Medium Text" android:id="#+id/Drive_Time_List" android:layout_alignParentTop="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" /> </RelativeLayout> And lastly, you just need to populate that ListView you created in the first step with this new adapter class. So use the following method (populates the ListView instead of using the for loop): private void populateView() { this.getActivity().runOnUiThread(new Runnable() { #Override public void run() { drives = APIRequestsUtil.getRoutes(); driveNumber = (TextView) myView.findViewById(R.id.Drive_Number); driveDistance = (TextView) myView.findViewById(R.id.Drive_Distance); driveTime = (TextView) myView.findViewById(R.id.Drive_Time); driveNumber.setText("Drive Number"); driveDistance.setText("Drive Distance"); driveTime.setText("Drive Time"); // edit: you need to generate your List data from the entrySet // the ArrayAdapter cannot take a Set argument - needs to be a List List<Map.Entry> list = new ArrayList<Map.Entry>(); for (Map.Entry drive : drives.entrySet()) { list.add(drive); } // populate the ListView // may need to change "getActivity()" to something else // this constructor needs the "this" context of the activity DriveListAdapter drivesListAdapter = new DriveListAdapter(getActivity(), list); ListView listView = (ListView)findViewById(R.id.listView); listView.setAdapter(drivesListAdapter); } }); }
first of all you use LinearLayout instead of TableLayoyt <LinearLayout android:id="#+id/llMainLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical"> try this code LinearLayout llMain=(LinearLayout) myView.findViewById(R.id.llMainLayout); for (Map.Entry drive : drives.entrySet()) { LinearLayout tr = new LinearLayout(getActivity()); tr.setOrientation(1); // horizontal Route route = (Route) drive.getValue(); tr.setId(driveNum++); // set params DateTime startTime = new DateTime(route.getStart_time()); DateTime endTime = new DateTime(route.getEnd_time()); TextView driveNumList = new TextView(); TextView driveDistList = new TextView(); TextView driveTimeList = new TextView(); driveNumList.setText(String.valueOf(driveNum)); driveDistList.setText(Double.parseDouble(route.getLen()) / 1000 + " km"); driveTimeList.setText((endTime.getMillis() - startTime.getMillis())/ 1000 + " s"); tr.addView(driveNumList); tr.addView(driveDistList); tr.addView(driveTimeList); llMain.addView(tr); } }
Android. How to change tab text color?
I want to set color of the tab text white, i cant find any good tutorial. Can someone help me? There is my tab activity: package com.example.dev.nordugrid; import android.app.TabActivity; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TabHost; import android.widget.TextView; import android.widget.Toast; import android.widget.TabHost.TabSpec; import java.util.ArrayList; import java.util.List; import java.util.Random; #SuppressWarnings("deprecation") public class Busena extends TabActivity { SharedPreferences prefs; TextView proxySuteike, proxyGaliojimas; Button button4; public int randomInt; String stringProxyGaliojimas, stringProxySuteike, stringUzduotiesPav, stringUzduotiesJDL, stringKitiFailai; Button holder; private ArrayList<Item> m_parts = new ArrayList<Item>(); private Runnable viewParts; private ItemAdapter m_adapter; private final String data[] = { "Android", "iPhone", "BlackBerry", "AndroidPeople" }; private final String data2[] = { "Ivykdyta", "Atsaukta", "Einama", "Nusisnekejo" }; List<String> a = new ArrayList<String>(); List<String> b = new ArrayList<String>(); public static void setDefaults(String key, String value, Context context) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = prefs.edit(); editor.putString(key, value); editor.commit(); } public static String getDefaults(String key, Context context) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); return preferences.getString(key, null); } #Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); this.setContentView(R.layout.activity_busena); this.setTheme(R.style.listItem); holder = (Button)findViewById(R.id.button19); proxyGaliojimas = (TextView)findViewById(R.id.generatenumber); proxySuteike = (TextView) findViewById(R.id.textView5); randomInt = Integer.parseInt(getDefaults("proxy", this)); stringProxySuteike = getDefaults("vo", this); proxyGaliojimas.setText(randomInt + " min."); proxySuteike.setText(stringProxySuteike); stringUzduotiesPav = getDefaults("uzduotiesPav", this); stringUzduotiesJDL = getDefaults("jdlFailoReiksme", this); stringKitiFailai = getDefaults("kitiFailaiReiksme", this); ListView list = (ListView)findViewById(R.id.tab1); m_parts.add(new Item(stringUzduotiesPav, stringUzduotiesJDL)); m_adapter = new ItemAdapter(this, R.layout.row, m_parts); list.setAdapter(m_adapter); button4 = (Button) findViewById(R.id.refreshProxy); TabHost tabHost = getTabHost(); this.setNewTab(this, tabHost, "tab1", R.string.uzduotys, android.R.drawable.star_on, R.id.tab1); this.setNewTab(this, tabHost, "tab2", R.string.proxy, android.R.drawable.star_on, R.id.tab2); addListenerOnButton(); } /*#Override protected void onListItemClick(ListView l, View v, int position, long id) { String item = (String) getListAdapter().getItem(position); Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show(); }*/ private void setNewTab(Context context, TabHost tabHost, String tag, int title, int icon, int contentID ) { TabSpec tabSpec = tabHost.newTabSpec(tag); String titleString = getString(title); tabSpec.setIndicator(titleString, context.getResources().getDrawable(android.R.drawable.star_on)); tabSpec.setContent(contentID); tabHost.addTab(tabSpec); } public void addListenerOnButton() { button4.setOnClickListener(new View.OnClickListener() { #Override public void onClick(View v) { int skaicius = randomInt; Random randomGenerator = new Random(); int rand = randomGenerator.nextInt(240-skaicius); String ats = Integer.toString(randomInt); proxyGaliojimas.setText(ats + " min."); randomInt = rand; } }); } } And this is what I see : This is tab activity xml file: <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" android:paddingLeft="#dimen/activity_horizontal_margin" android:paddingRight="#dimen/activity_horizontal_margin" android:paddingTop="#dimen/activity_vertical_margin" android:paddingBottom="#dimen/activity_vertical_margin" tools:context="com.example.dev.nordugrid.Busena" android:background="#drawable/background" > <TabHost android:id="#android:id/tabhost" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_alignParentTop="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" > <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <TabWidget android:theme="#style/listItem" android:id="#android:id/tabs" android:layout_width="fill_parent" android:layout_height="wrap_content"></TabWidget> <FrameLayout android:id="#android:id/tabcontent" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ListView android:id="#+id/tab1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" /> <LinearLayout android:id="#+id/tab2" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <!-- antro tabo vaizdas --> <TextView android:layout_marginTop="3dp" android:id="#+id/textView3" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="#string/proxyGaliojimas" android:textColor="#FFFBFB" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:layout_marginLeft="7dp" android:layout_marginTop="3dp" android:id="#+id/generatenumber" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="#string/min" android:textColor="#FFFBFB" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:layout_marginTop="3dp" android:id="#+id/textView4" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="#string/proxySuteike" android:textColor="#FFFBFB" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:layout_marginLeft="7dp" android:layout_marginTop="3dp" android:id="#+id/textView5" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="#string/proxySuteike" android:textColor="#FFFBFB" android:textAppearance="?android:attr/textAppearanceMedium" /> <Button android:layout_marginTop="7dp" android:id="#+id/refreshProxy" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="#string/atnaujinti" android:textColor="#FFFBFB" android:background="#drawable/border"/> </LinearLayout> </FrameLayout> </LinearLayout> </TabHost> Please someone give me simple example or other help :)
Create this method:- private static View createTabView(Context context, String tabText) { View view = LayoutInflater.from(context).inflate(R.layout.custom_tab, null, false); TextView tv = (TextView) view.findViewById(R.id.tabTitleText); tv.setText(tabText); return view; } Create custom_tab.xml file in layout folder <?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="#+id/tabTitleText" android:layout_width="#dimen/tabWidth" android:layout_height="wrap_content" android:gravity="center_horizontal" android:clickable="true" android:paddingTop="#dimen/tabTopPading" android:paddingBottom="#dimen/tabBottomPading" android:paddingLeft="#dimen/tabLeftPading" android:paddingRight="#dimen/tabRightPading" android:textSize="#dimen/tabTextSize" android:textColor="#color/themeColor" android:background="#drawable/tab_selector"/> finally set tabHost.newTabSpec("Tab1").setIndicator(createTabView(getApplicationContext(),"Tab_name"))