TextView crash? - android

public class MainActivity extends Activity {
TextView tID;
TextView tName;
TextView tWorld;
protected void onCreate(Bundle paramBundle) {
super.onCreate(paramBundle);
setContentView(R.layout.ps);
tID = (TextView) findViewById(R.id.tID);
tName = (TextView) findViewById(R.id.tName);
tWorld = (TextView) findViewById(R.id.tWorld);
}
public void Search(View view) {
int clist = -2;
String oID = "";
String oName = "";
String oWorld = "";
setContentView(R.layout.list);
while (clist != -1)
{
oID = tID.getText().toString();
tID.setText(oID+"ddf"+"\n");
oName = tName.getText().toString();
clist = -1;
}
}
}
list.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/VScroll"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="3" >
<TextView
android:id="#+id/tID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text=" " />
<TextView
android:id="#+id/tName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text=" " />
<TextView
android:id="#+id/tWorld"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text=" " />
</LinearLayout>
</ScrollView>
I know this is probably really simple but looking online doesn't answer it...
why does this crash upon getting to here?:
I know this is probably really simple but looking online doesn't answer it...
why does this crash upon getting to here?:
while (clist != -1)
{
oID = tID.getText().toString();
tID.setText(oID+"ddf"+"\n");
oName = tName.getText().toString();
clist = -1;
}
Edit*
Search() is an onClick button in ps.xml while the textview are in list.xml

Inside your onCreate() method:
change from setContentView(R.layout.ps); to setContentView(R.layout.list); because you are using list.xml as your main layout.
and delete this line setContentView(R.layout.list); inside your Search() method:
public void Search(View view) {
int clist = -2;
String oID = "";
String oName = "";
String oWorld = "";
// Delete this line setContentView(R.layout.list);
while (clist != -1)
{
oID = tID.getText().toString();
tID.setText(oID+"ddf"+"\n");
oName = tName.getText().toString();
clist = -1;
}
}

Related

custom view with overlapping

I define layout row which I inflate and add view pragmatically to a linear layout.
I wanna something like this,
https://i.stack.imgur.com/EKPmJ.png
Here is xml of my main activity where I am inflating the costume view row
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.skw.customeviewdemo.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/inflate"
android:text="inflate"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/list_container">
</LinearLayout>
</LinearLayout>
here is my xml code of row which I am inflating:
<?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"
android:orientation="horizontal">
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="its text view"
/>
<Button
android:id="#+id/nameButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/name"
/>
<ImageView
android:layout_marginTop="-25dp"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#mipmap/ic_launcher_round"/>
</RelativeLayout>
here is my java code
public class MainActivity extends AppCompatActivity {
Button b;
LinearLayout l1;
Context context;
Boolean isViewCreated = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String Namearray[] = {"sagar", "ranjeet", "akash", "kate"};
this.context = this;
b = (Button) findViewById(R.id.inflate);
l1 = (LinearLayout) findViewById(R.id.list_container);
createViews(Namearray);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(l1.getVisibility() == View.VISIBLE && isViewCreated)
{
l1.setVisibility(View.GONE);
}
else
{
l1.setVisibility(View.VISIBLE);
}
}
});
}
void createViews(final String[] namearray)
{
for(int i=0;i < namearray.length;i++){
final int j = i;
View view = LayoutInflater.from(context).inflate(R.layout.layout_item,null);
TextView button1 = (TextView) view.findViewById(R.id.name);
Button button2 = (Button) view.findViewById(R.id.nameButton);
button1.setText("HELLO " + namearray[i]);
button2.setText("Click to know my name ");
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,"Hello " + namearray[j],Toast.LENGTH_LONG).show();
}
});
view.setId(generateViewId());
try {
l1.addView(view);
isViewCreated = true;
}
catch (Exception e)
{
}
}
l1.setVisibility(View.GONE);
}
private static final AtomicInteger viewIdGenerator = new AtomicInteger(15000000);
public static int generateViewId() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
return generateUniqueViewId();
} else {
return View.generateViewId();
}
}
private static int generateUniqueViewId() {
while (true) {
final int result = viewIdGenerator.get();
// aapt-generated IDs have the high byte nonzero; clamp to the range under that.
int newValue = result + 1;
if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
if (viewIdGenerator.compareAndSet(result, newValue)) {
return result;
}
}
}
}
but when I inflate row my image view get cutoff which I not want I tried with negative margin but it not work
here what it looks like
custom overlapping row
what I do so I over lap image to above view?
Try changing your layout to this.
<?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"
android:orientation="horizontal">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="its text view"
/>
<Button
android:id="#+id/nameButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/name"
/>
</RelativeLayout>
<ImageView
android:layout_marginTop="25dp"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#mipmap/ic_launcher_round"/>
</RelativeLayout>
When you put in another row, that row needs to be pushed up so the android icon that is there now overlays it.

Erratic behaviour of onclick method in listview

I have a listview and each item in the listview contains a button.
There is the method which is called when the button is clicked.
The expected behaviour is that the text is changed to red and the size of the text is increased.
Now this works perfectly fine when the listview fits within the screen. However, when the listview doesn't fit in the screen,
if I press the button of the first item that doesn't fit, both that item AND the first item in the listview get highlighted. Similarly,
if I press the first item in the listview, both that and the first item that doesn't fit get highlighted.
I'm assuming I need to use the position variable somehow solve this problem however I am failing to identify what the problem is.
public void clicking(View v) {
Button b = (Button) v;
LinearLayout layout = (LinearLayout) v.getParent();
String buttontext = b.getText().toString();
TextView betidtextbox = (TextView) layout.findViewById(R.id.gid);
LinearLayout layoutt = (LinearLayout) layout.getParent();
String betid = betidtextbox.getText().toString();
if (b.getTag() == "highlighted") {
b.setTextColor(Color.parseColor("#000000"));
b.setTextSize(18);
b.setTag("");
selection = "home";
else {
b.setTextColor(Color.parseColor("#EB102E"));
b.setTextSize(20);
b.setTag("highlighted");
selection = "home";
Activity code:
public class AllGameslistActivity extends ListActivity {
private Bet newBet = new Bet();
private double stake = 0.00;
private String name = "";
private double newwinnings;
private String newwinningstoString;
private View itemView;
private String selection;
private ArrayList<TipDisplayer> tomee = new ArrayList<>();
// Progress Dialog
private static String url_all_games = "***";
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> gamesList;
// url to get all products list
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_GAMELIST = "gamelist";
private static final String TAG_ID = "ID";
private static final String TAG_LEAGUE = "League";
private static final String TAG_TEAMS = "Teams";
private static final String TAG_BET = "Bet";
private static final String TAG_ODDS = "Odds";
private static final String TAG_DATETIMER = "DateTimer";
private static final String TAG_COMMENTS = "Comments";
private static final String TAG_TYPE = "Type";
// products JSONArray
JSONArray allgames = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_bets);
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
menu menu = (menu) getFragmentManager().findFragmentById(R.id.fragment);
menu.betnowclick();
SessionManager session;
session = new SessionManager(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
name = user.get(SessionManager.USERNAME);
menu.updateinfo(getName());
// Hashmap for ListView
gamesList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllGames().execute();
// Get listview
ListView lv = getListView();
}
/**
* Background Async Task to Load all product by making HTTP Request
*/
class LoadAllGames extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
}
/**
* getting All products from url
*/
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_games, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Games: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Games
allgames = json.getJSONArray(TAG_GAMELIST);
// looping through All Products
for (int i = 0; i < allgames.length(); i++) {
JSONObject c = allgames.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String league = c.getString(TAG_LEAGUE);
String odds = c.getString(TAG_ODDS);
String comments = c.getString(TAG_COMMENTS);
String type = c.getString(TAG_TYPE);
String bet = c.getString(TAG_BET);
String datetimer = c.getString(TAG_DATETIMER);
String Teams = c.getString(TAG_TEAMS);
Double Odds = Double.parseDouble(odds);
// 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_LEAGUE,league);
map.put(TAG_ODDS,odds);
map.put(TAG_COMMENTS,comments);
map.put(TAG_TYPE,type);
map.put(TAG_BET,bet);
map.put(TAG_DATETIMER,datetimer);
map.put(TAG_TEAMS, Teams);
Log.d("id", id);
Log.d("league", league);
Log.d("odds", odds);
Log.d("comments", comments);
Log.d("Type", type);
Log.d("bet", bet);
Log.d("datetimer", datetimer);
Log.d("teams",Teams);
tomee.add(i, new TipDisplayer(id, league, Teams, bet, odds, datetimer, comments, type));
// adding HashList to ArrayList
gamesList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return "";
}
/**
* After completing background task Dismiss the progress dialog
* *
*/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
// updating UI from Background Thread
PopulateList();
}
}
private class MyListAdapter extends ArrayAdapter<TipDisplayer> {
public MyListAdapter() {
super(AllGameslistActivity.this, R.layout.list_item, tomee);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
itemView = convertView;
if (itemView == null) {
itemView = getLayoutInflater().inflate(R.layout.list_item, parent, false);
}
TextView leaguetxt = (TextView) itemView.findViewById(R.id.leaguetxt);
TextView datetxt = (TextView) itemView.findViewById(R.id.datetxt);
TextView teamstxt = (TextView) itemView.findViewById(R.id.teamstxt);
TextView bettxt = (TextView) itemView.findViewById(R.id.bettxt);
TextView betid = (TextView) itemView.findViewById(R.id.gid);
TextView typetxt = (TextView) itemView.findViewById(R.id.difficultytxt);
TextView commentstxt = (TextView) itemView.findViewById(R.id.commenttxt);
Button oddsbtn = (Button) itemView.findViewById(R.id.oddsbutton);
TipDisplayer currentwriter = tomee.get(position);
String leaguetext = currentwriter.getLeague();
String datetext = currentwriter.getDatetimer();
String teamstext = currentwriter.getTeams();
String bettext = currentwriter.getBet();
String typetext = currentwriter.getType();
String idtext = currentwriter.getId();
String commentsText = currentwriter.getComments();
String oddstext = currentwriter.getOdds();
leaguetxt.setText(leaguetext);
datetxt.setText(datetext.substring(0,datetext.lastIndexOf(":")) + " GMT");
teamstxt.setText(teamstext);
bettxt.setText(bettext);
betid.setText(idtext);
commentstxt.setText(commentsText);
oddsbtn.setText(oddstext);
typetxt.setText(typetext);
if (typetext.equals("Low Risk")) {
typetxt.setTextColor(Color.parseColor("#067103"));
}
else if (typetext.equals("Medium Risk")) {
typetxt.setTextColor(Color.parseColor("#D9D216"));
}
else if (typetext.equals("Longshot")) {
typetxt.setTextColor(Color.parseColor("#F75528"));
}
return itemView;
}
}
private void PopulateList() {
ArrayAdapter<TipDisplayer> adapter = new MyListAdapter();
final ListView list = (ListView) findViewById(R.id.mylist);
list.setAdapter(adapter);
}
public void SelectBet(View v) {
clicking(v);
}
public void clicking(View v) {
Button b = (Button) v;
ListView lv = getListView();
int position = lv.getPositionForView(v);
LinearLayout layout = (LinearLayout) v.getParent();
String buttontext = b.getText().toString();
TextView betidtextbox = (TextView) layout.findViewById(R.id.gid);
LinearLayout layoutt = (LinearLayout) layout.getParent();
String betid = betidtextbox.getText().toString();
if (b.getTag().toString().equals("highlighted")) {
b.setTextColor(Color.parseColor("#000000"));
b.setTextSize(18);
b.setTag("");
selection = "home";
TextView teamss = (TextView) layoutt.findViewById(R.id.teamstxt);
String teams = teamss.getText().toString();
newBet.generateoddstesting(betid, buttontext, false,teams,selection);
double newodds = newBet.calculateodds();
TextView myBetOdds = (TextView) findViewById(R.id.bettingodds);
TextView potentialWinnings = (TextView) findViewById(R.id.potentialwinnings);
myBetOdds.setText("#" + String.format("%.2f", newodds) + "/1");
EditText mEdit = (EditText) findViewById(R.id.editText2);
if (mEdit.getText().toString().length() == 0) {
stake = 0.00;
newwinnings = 0.00;
potentialWinnings.setText("0.00");
} else {
mEdit.addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
if (s.length() != 0) {
stake = Double.parseDouble(s.toString());
double newodds = newBet.calculateodds();
newwinnings = stake * newodds;
TextView myBetOdds = (TextView) findViewById(R.id.bettingodds);
TextView potentialWinnings = (TextView) findViewById(R.id.potentialwinnings);
myBetOdds.setText("#" + String.format("%.2f",newodds) + "/1");
potentialWinnings.setText(String.format("%.2f", (newwinnings)));
newwinningstoString = potentialWinnings.getText().toString();
} else {
stake = 0.00;
newwinnings = 0.00;
double newodds = newBet.calculateodds();
TextView myBetOdds = (TextView) findViewById(R.id.bettingodds);
TextView potentialWinnings = (TextView) findViewById(R.id.potentialwinnings);
myBetOdds.setText("#" + String.format("%.2f",newodds) + "/1");
potentialWinnings.setText(String.format("%.2f", (newwinnings)));
newwinningstoString = potentialWinnings.getText().toString();
}
}
public void afterTextChanged(Editable s) {
}
});
//stake = Double.parseDouble(mEdit.getText().toString());
newwinnings = stake*newodds;
potentialWinnings.setText(String.format("%.2f", (newwinnings)));
newwinningstoString = potentialWinnings.getText().toString();
}
} else {
b.setTextColor(Color.parseColor("#EB102E"));
b.setTextSize(20);
b.setTag("highlighted");
selection = "home";
String getodds = b.getText().toString();
EditText mEdit = (EditText) findViewById(R.id.editText2);
if (mEdit.getText().toString().length() == 0) {
stake = 0.00;
newwinnings = 0.00;
TextView potentialWinnings = (TextView) findViewById(R.id.potentialwinnings);
potentialWinnings.setText("0.00");
} else {
mEdit.addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
if (s.length() != 0) {
stake = Double.parseDouble(s.toString());
double newodds = newBet.calculateodds();
newwinnings = stake * newodds;
TextView myBetOdds = (TextView) findViewById(R.id.bettingodds);
TextView potentialWinnings = (TextView) findViewById(R.id.potentialwinnings);
myBetOdds.setText("#" + String.format("%.2f",newodds) + "/1");
potentialWinnings.setText(String.format("%.2f", (newwinnings)));
newwinningstoString = potentialWinnings.getText().toString();
} else {
stake = 0.00;
double newodds = newBet.calculateodds();
newwinnings = stake * newodds;
TextView myBetOdds = (TextView) findViewById(R.id.bettingodds);
TextView potentialWinnings = (TextView) findViewById(R.id.potentialwinnings);
myBetOdds.setText("#" + String.format("%.2f",newodds) + "/1");
potentialWinnings.setText(String.format("%.2f", (newwinnings)));
newwinningstoString = potentialWinnings.getText().toString();
}
}
public void afterTextChanged(Editable s) {
}
});
stake = Double.parseDouble(mEdit.getText().toString());
TextView teamms = (TextView) layoutt.findViewById(R.id.teamstxt);
String teams = teamms.getText().toString();
newBet.generateoddstesting(betid, buttontext, true,teams,selection);
double newodds = newBet.calculateodds();
newwinnings = stake * newodds;
TextView myBetOdds = (TextView) findViewById(R.id.bettingodds);
TextView potentialWinnings = (TextView) findViewById(R.id.potentialwinnings);
myBetOdds.setText("#" + String.format("%.2f",newodds) + "/1");
potentialWinnings.setText(String.format("%.2f", (newwinnings)));
newwinningstoString = potentialWinnings.getText().toString();
}
}
}
list_item layout :
<?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:background="#drawable/whatisthis"
android:weightSum="160">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="20"
android:orientation="horizontal"
android:weightSum="100">
<TextView
android:layout_width="0dp"
android:id="#+id/leaguetxt"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="50"
android:gravity="center"
android:text="English Premier League"
android:textColor="#067103"
android:textStyle="bold" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/datetxt"
android:layout_gravity="center"
android:layout_weight="50"
android:gravity="center"
android:text="BET UNTIL : 23/05/2015 15:00 GMT"
android:textColor="#067103"
android:textSize="12sp"
android:textStyle="italic" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="30">
<TextView
android:id="#+id/teamstxt"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="left"
android:gravity="left|center"
android:text="Sevilla FC - FC Barcelona"
android:textColor="#067103"
android:textSize="20sp"
/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="30"
android:orientation="horizontal">
<!-- Name Label -->
<TextView
android:layout_width="0dp"
android:id="#+id/bettxt"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:layout_weight="30"
android:gravity="center"
android:textSize="23sp"
android:text="FC Barcelona Win and BTTS"
android:textColor="#067103"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_weight="20"
android:weightSum="100"
android:orientation="horizontal"
android:layout_height="0dp">
<TextView
android:id="#+id/difficultytxt"
android:layout_weight="100"
android:layout_gravity="center"
android:gravity="center"
android:textColor="#067103"
android:text="MEDIUM RISK"
android:layout_width="0dp"
android:layout_height="fill_parent" />
</LinearLayout>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="fill_parent"
android:id="#+id/commenttxt"
android:textStyle="italic"
android:layout_height="wrap_content"
android:textColor="#067103"
android:text = " "/>
</ScrollView>
<LinearLayout
android:layout_width="fill_parent"
android:layout_weight="20"
android:weightSum="100"
android:orientation="horizontal"
android:layout_height="0dp">
<TextView
android:layout_width="0dp"
android:layout_weight="40"
android:layout_height="fill_parent" />
<Button
android:id="#+id/oddsbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="20"
android:layout_gravity="center"
android:tag = ""
android:gravity="center"
android:onClick="SelectBet"
android:text="3.60"
android:textColor="#000000"
android:textSize="18sp" />
<TextView
android:layout_width="0dp"
android:layout_height="0dp"
android:id = "#+id/gid"
android:visibility="gone"/>
</LinearLayout>
</LinearLayout>
XML Code of Activity :
<?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="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<LinearLayout
android:id="#+id/bottom_control_bar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#drawable/timeleft"
android:orientation="horizontal"
android:weightSum="100">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="5"
android:text="Stake"
android:gravity="center"
android:textColor="#FFFFFF"
android:layout_gravity="center"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textSize="14dp"
android:textStyle="bold" />
<EditText
android:id="#+id/editText2"
android:layout_width="0dp"
android:layout_weight="30"
android:layout_height="fill_parent"
android:ems="10"
android:textColorHint="#FFFFFF"
android:textColor="#FFFFFF"
android:hint="0"
android:gravity="center_vertical"
android:inputType="number" />
<LinearLayout
android:layout_width="0dp"
android:layout_weight="65"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="18dp"
android:layout_gravity="top"
android:layout_marginBottom="-5dp"
android:includeFontPadding="false"
android:text="#string/potentialwinnings"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#FFFFFF"
android:textStyle="bold" />
<TextView
android:id="#+id/bettingodds"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:gravity="bottom"
android:text="\#1.00/1"
android:textColor="#FFFFFF"
android:textSize="12dp"
android:textStyle="italic">
</TextView>
<TextView
android:id="#+id/potentialwinnings"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_gravity="left"
android:gravity="bottom"
android:text="0.00"
android:textColor="#FFFFFF"
android:textSize="16sp"
android:textStyle="bold" />
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_weight="5"
android:textColor="#FFFFFF"
android:textSize="15sp"
android:onClick="NewBetMaker"
android:text="Save Bet!"></Button>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/bottom_control_bar"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:orientation="vertical">
<!-- Main ListView
Always give id value as list(#android:id/list)
-->
<fragment
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:name="com.example.albert.betterapp.menu"
android:id="#+id/fragment"
tools:layout="#layout/fragment_menu" />
<ListView
android:id="#+id/mylist"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/bottom_control_bar" />
<ListView
android:id="#android:id/list"
android:layout_width="0dp"
android:visibility="gone"
android:layout_height="0dp"
/>
</LinearLayout>
</RelativeLayout>
So each item in the listview has a button, when I click on the button for the first item in the listview, the onclick method is run for both the first item and the first not visible item, if I do it for the second item, its run for the second item and the second not visible item. Similarly if I scroll down and click the first not visible item, its run for that item and the first item and the pattern continues.
inside your getView() you could use OnClickListener:
oddsbtn.setText(oddstext);
oddsbtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// Do whatever you want, view v is your button.
});
I noticed you just added getPositionForView() call from the ListView. This is not a reliable way to do it. The reason is the position in the AdapterView is not well defined. It is not directly related to which row is being selected. The documentation does not even say it is.
However you should be able to achieve your goal by adding code onto the Adapter. I don't have much time right now. For now, please read up a good webpage tutorial # Android Listview.
Please look at code snippet from the page:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
...
EDIT 1:
One suspect code is that you need to pass the ArrayList to the Adapter. You should not depend on the static object tomee. Adapters prefer objects that are stable and "final".
Change FROM:
private void PopulateList() {
ArrayAdapter<TipDisplayer> adapter = new MyListAdapter();
TO:
private void PopulateList() {
ArrayAdapter<TipDisplayer> adapter = new MyListAdapter(tomee);
Add:
public MyListAdapter(ArrayList<TipDisplayer> tomee) {
super(AllGameslistActivity.this, R.layout.list_item, tomee);
this.tomee = tomee; // declare tomee in the Adapter, don't use static
}
Note:
In the Adapter, add another constructor to accept the ArrayList, supporting the change in PopulateList().
The other suspect code (in my opinion) is calling PopulateList() in onPostExecute(). This is a clever idea, I think, but I am not sure of its reliability, need further thought. Fix the one above first.

Convert gdata feed to xml - Youtube Playlist to ANdroid Listview

I am following this code to create a custom list view.
It uses an XML file to parse objects and show them in Listview
I was wondering can I use the same example to show Videos Titles and Duration of a Youtube Playlist.
I have gone though Youtube API and GDATA but I can't find out how to get raw xml link which I can use with above example code
Any help guys?
Heres a class I've used in one of my previous projects. This puts the first video as the "main" one, displays the time and title, and then adds all the rest of the videos to a layout.
public class Videos extends Activity {
ImageView mainThumb;
TextView mainTitle;
TextView mainTime;
LinearLayout videos;
ArrayList<String> links;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.videos);
new ParseVideoDataTask().execute();
mainThumb = (ImageView) findViewById(R.id.mainThumb);
mainTitle = (TextView) findViewById(R.id.mainTitle);
mainTime = (TextView) findViewById(R.id.mainTime);
videos = (LinearLayout) findViewById(R.id.videos);
}
private class ParseVideoDataTask extends AsyncTask<String, String, String> {
int count = 0;
#Override
protected String doInBackground(String... params) {
URL jsonURL;
URLConnection jc;
links = new ArrayList<String>();
try {
jsonURL = new URL("http://gdata.youtube.com/feeds/api/playlists/" +
YOUR PLAYLIST ID +
"?v=2&alt=jsonc");
jc = jsonURL.openConnection();
InputStream is = jc.getInputStream();
String jsonTxt = IOUtils.toString(is);
JSONObject jj = new JSONObject(jsonTxt);
JSONObject jdata = jj.getJSONObject("data");
JSONArray aitems = jdata.getJSONArray("items");
for (int i=0;i<aitems.length();i++) {
JSONObject item = aitems.getJSONObject(i);
JSONObject video = item.getJSONObject("video");
String title = video.getString("title");
JSONObject player = video.getJSONObject("player");
String link = player.getString("default");
String length = video.getString("duration");
JSONObject thumbnail = video.getJSONObject("thumbnail");
String thumbnailUrl = thumbnail.getString("hqDefault")
String[] deets = new String[4];
deets[0] = title;
deets[1] = thumbnailUrl;
deets[2] = length;
links.add(link);
publishProgress(deets);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(final String... deets) {
count++;
if (count == 1) {
MainActivity.setImageFromUrl(deets[1], mainThumb, Videos.this);
mainTitle.setText(deets[0]);
mainTime.setText(formatLength(deets[2]));
mainThumb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(links.get(1)));
startActivity(i);
}
});
} else {
LayoutInflater layoutInflater = (LayoutInflater)Videos.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View video = layoutInflater.inflate(R.layout.video, null);
ImageView thumb = (ImageView) video.findViewById(R.id.thumb);
TextView title = (TextView) video.findViewById(R.id.title);
TextView time = (TextView) video.findViewById(R.id.time);
MainActivity.setImageFromUrl(deets[1], thumb, Videos.this);
title.setText(deets[0]);
time.setText(formatLength(deets[2]));
video.setPadding(20, 20, 20, 20);
videos.addView(video);
video.setId(count-1);
video.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(links.get(v.getId())));
startActivity(i);
}
});
}
}
}
private CharSequence formatLength(String secs) {
int secsIn = Integer.parseInt(secs);
int hours = secsIn / 3600,
remainder = secsIn % 3600,
minutes = remainder / 60,
seconds = remainder % 60;
return ((minutes < 10 ? "0" : "") + minutes
+ ":" + (seconds< 10 ? "0" : "") + seconds );
}
#Override
public void onDestroy() {
super.onDestroy();
for (int i=0;i<videos.getChildCount();i++) {
View v = videos.getChildAt(i);
if (v instanceof ImageView) {
ImageView iv = (ImageView) v;
((BitmapDrawable)iv.getDrawable()).getBitmap().recycle();
}
}
}
}
video.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"
android:orientation="vertical" >
<ImageView
android:id="#+id/thumb"
android:layout_width="240dp"
android:layout_height="180dp"
android:layout_centerHorizontal="true"
android:scaleType="fitStart" />
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/thumb"
android:layout_below="#+id/thumb"
android:layout_toLeftOf="#+id/time"
android:maxLines="1"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#android:color/black" />
<TextView
android:id="#+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/thumb"
android:layout_below="#+id/thumb"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#android:color/black" />
</RelativeLayout>
videos.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"
android:background="#android:color/white"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="#+id/mainThumb"
android:layout_width="240dp"
android:layout_height="180dp"
android:layout_centerHorizontal="true"
android:scaleType="fitXY"/>
<TextView
android:id="#+id/mainTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/mainThumb"
android:layout_below="#+id/mainThumb"
android:layout_toLeftOf="#+id/mainTime"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#android:color/black" />
<TextView
android:id="#+id/mainTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/mainThumb"
android:layout_below="#+id/mainThumb"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#android:color/black" />
</RelativeLayout>
<HorizontalScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbars="none"
android:layout_alignParentBottom="true" >
<LinearLayout
android:id="#+id/videos"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:gravity="center"
android:orientation="horizontal" />
</HorizontalScrollView>
</RelativeLayout>

Populate android contacts

i want to choose the contacts from a list view (which seems to work) - and populate the chosen contact in another ui (and then send a generated message to the chosen contact by sms). The populateField method doesn't work.
Here snippets from my code:
the 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:background="#color/yellow"
android:orientation="vertical" >
<TextView
android:id="#+id/label_sms_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/label_sms_number"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/black" />
<TextView
android:id="#+id/display_sendSms_name_contact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/black" />
<TextView
android:id="#+id/display_sendSms_contact_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/black" />
<TextView
android:id="#+id/label_sms_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/label_sms_message"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/black" />
<EditText
android:id="#+id/input_sms_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textMultiLine" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button_sms_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/label_sms_button_send" />
</LinearLayout>
my java code:
public class SendSMS extends Activity{
private IShoppingListDao shoppingManager;
private TextView mContact;
private TextView mMessage;
private Long mRowId;
private static final String TAG = "SendSMS";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.send_list_by_sms);
shoppingManager = new ShoppingListDao(this);
shoppingManager.open();
mContact = (TextView) findViewById(R.id.display_sendSms_name_contact);
mRowId = null;
Bundle extras = getIntent().getExtras();
mRowId = (savedInstanceState == null) ? null : (Long) savedInstanceState
.getSerializable(ContactsContract.Contacts.DISPLAY_NAME);
Log.d(TAG, "Row-id: "+mRowId);
if (extras != null) {
mRowId = extras.getLong(ContactsContract.Contacts.DISPLAY_NAME);
}
mMessage = (TextView) findViewById(R.id.input_sms_message);
mMessage.setText(generateMessage());
populateFields();
}
private void populateFields() {
Log.d(TAG,"Entering populateFields");
Log.d(TAG,"Row-id: "+mRowId);
if (mRowId != null) {
ContentResolver cr = getContentResolver();
String where = ContactsContract.Contacts._ID + " = " + mRowId;
Log.d(TAG,"String where: "+where);
//selecting the name
Cursor listItem = cr.query(
ContactsContract.Contacts.CONTENT_URI,
null,
where,
null, null);
startManagingCursor(listItem);
mContact.setText(listItem.getString(
listItem.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
}
}

Android: archiving items in listview

I'm having a listview in which I'm displaying the text items. I want to display a checkbox along with the text for two type of actions to be performed. one is when the user click on the list item it should take to another activity and another is the user can select the checkbox of the list item and can move the items to some groups. As similar to that we do in the gmail inbox. how can i do it ? Any help ?
Here I attach my code.
keywords.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/keywordlayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/background_gradient"
android:orientation="vertical"
>
<LinearLayout
android:id="#+id/category_title_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:background="#fff"
>
<TextView
android:id="#+id/category_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
android:textColor="#000"
android:textStyle="italic"
android:typeface="sans"
android:gravity="center"
/>
</LinearLayout>
<ListView
android:id="#+id/keywordslist"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/background_gradient"
>
</ListView>
</LinearLayout>
The xml file used for displaying list items layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/list_display"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<CheckBox
android:id="#+id/chk_box"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:visibility="invisible"
>
</CheckBox>
<TextView
android:id="#+id/key_id"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
>
</TextView>
<TextView
android:id="#+id/key_name"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp"
android:textColor="#FFF">
</TextView>
</LinearLayout>
and my java code for the activity
package com.sample.epiphron;
public class KeywordsList extends Activity {
TextView category_title;
ListView keywords_list ;
String categoryid, categoryname;
private ArrayList<KeywordDetails> listItems = new ArrayList<KeywordDetails>();
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.keywords);
Bundle extras = getIntent().getExtras();
categoryid = extras.getString("category_id");
categoryname = extras.getString("category_name");
category_title = (TextView) findViewById(R.id.category_title);
category_title.setText(""+categoryname+"- Keywords");
keywords_list = (ListView) findViewById(R.id.keywordslist);
drawList(LoginScreen.user_credential, categoryid);
//Toast.makeText(this, chkbx.toString(), Toast.LENGTH_SHORT).show();
keywords_list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
TextView txtv1 = (TextView) arg1.findViewById(R.id.key_id);
Toast.makeText(KeywordsList.this, txtv1.getText(), Toast.LENGTH_LONG).show();
}
});
}
public void drawList(String userid, String cat_id){
WebServiceCall res = new WebServiceCall();
SoapObject result = res.fetchKeyword(userid, cat_id);
ArrayList<String> al = new ArrayList<String>();
for (int i = 0; i<result.getPropertyCount(); i++){
SoapObject obj = (SoapObject) result.getProperty(i);
al.add((String) obj.getProperty("keywordname"));
KeywordDetails object = new KeywordDetails(Integer.parseInt(obj.getProperty("keywordid").toString()), obj.getProperty("keywordname").toString());
listItems.add(object);
}
for ( int j = 0; j < result.getPropertyCount(); j++ ) {
}
keywords_list.setAdapter(new ListItemsAdapter(listItems));
}
public class KeywordDetails{
private int keyword_id;
private String keyword_name;
public KeywordDetails(int key_id, String key_name){
this.keyword_id = key_id;
this.keyword_name = key_name;
}
public int getId(){
return this.keyword_id;
}
public String getName(){
return this.keyword_name;
}
//...
}
private class ListItemsAdapter extends ArrayAdapter<KeywordDetails> {
ArrayList<KeywordDetails> obj = null;
KeywordDetails keyworddtls = null;
public ListItemsAdapter(ArrayList<KeywordDetails> items) {
super(KeywordsList.this, android.R.layout.simple_list_item_1, items);
this.obj = items;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.keyword_list_item, null);
final TextView text1 = (TextView) convertView.findViewById(R.id.key_id);
TextView text2 = (TextView) convertView.findViewById(R.id.key_name);
CheckBox chkbx = (CheckBox) convertView.findViewById(R.id.chk_box);
keyworddtls = obj.get(position);
text1.setText(Integer.toString(keyworddtls.getId()));
text2.setText(keyworddtls.getName());
chkbx.setVisibility(View.VISIBLE);
return convertView;
}
}
}
Add the CheckBox in the xml where is your <ListView > or in the xml which you use as item layout. Then in the getView() instantiate the CheckBox along the TextView. Implement listview.setOnItemClickListener() and based on which item was clicked (position) you start the activity [matter of logic] For the grouped of check items you can use getCheckedItemPositions(). I hope this will give you fire up idea.

Categories

Resources