Erratic behaviour of onclick method in listview - android

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.

Related

How to send List View values to the another activity in android

i am creating a simple crud system in android.i can view all data in to Listview. if i select a item from the list view it going to another activity for edit. but pass data to the Another activity successfully. but how to assign to textfields. i can pass only one textfield. how to pass values in to the relavent textfields. i attached the screen shot and codes below
Screen Shots
view.xml
<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=".view">
<ListView
android:id="#+id/lst1"
android:layout_width="368dp"
android:layout_height="495dp"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp" />
</LinearLayout>
View.java
public class view extends AppCompatActivity {
ListView lst1;
ArrayList<String> titles = new ArrayList<String>();
ArrayAdapter arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
SQLiteDatabase db = openOrCreateDatabase("StudentDB", Context.MODE_PRIVATE, null);
lst1 = findViewById(R.id.lst1);
Cursor c = db.rawQuery("select * from record",null);
int id = c.getColumnIndex("id");
int name = c.getColumnIndex("name");
int age = c.getColumnIndex("age");
c.moveToFirst();
titles.clear();
arrayAdapter = new ArrayAdapter(this,R.layout.support_simple_spinner_dropdown_item,titles);
lst1.setAdapter(arrayAdapter);
if(c.moveToFirst()) {
do {
titles.add(c.getString(id) + " \t " + c.getString(name) + " \t " + c.getString(age));
} while (c.moveToNext());
arrayAdapter.notifyDataSetChanged();
lst1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String tt = titles.get(position).toString();
Intent i = new Intent(getApplicationContext(),edit.class);
i.putExtra("age",tt);
startActivity(i);
}
});
}
Edit.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity = "center"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Edit System"
android:textColor="#color/colorAccent"
android:textSize="40dp"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="ID" />
<EditText
android:id="#+id/id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Name" />
<EditText
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Age" />
<EditText
android:id="#+id/age"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:inputType="textPersonName" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal">
<Button
android:id="#+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Edit" />
<Button
android:id="#+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Delete" />
</LinearLayout>
Edit.java
public class edit extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit);
EditText ed1 = findViewById(R.id.age);
Intent i = getIntent();
String ttt = i.getStringExtra("age").toString();
ed1.setText(ttt);
}
}
Create one pojo class like
class student{
String id,
String name,
String age,
String titles
}
now replace below code
if(c.moveToFirst()) {
do {
titles.add(c.getString(id) + " \t " + c.getString(name) + " \t " + c.getString(age));
} while (c.moveToNext());
arrayAdapter.notifyDataSetChanged();
lst1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String tt = titles.get(position).toString();
Intent i = new Intent(getApplicationContext(),edit.class);
i.putExtra("age",tt);
startActivity(i);
}
});
with
ArrayList<student> stud = new ArrayList<student>();
if(c.moveToFirst()) {
do {
student stu = new student()
stu.id = c.getString(id);
stu.name = c.getString(name);
stu.age = c.getString(age);
//you need to add the Student object stu not the ArrayList Object stud
stud.add(stu);
titles.add(c.getString(id) + " \t " + c.getString(name) + " \t " + c.getString(age));
} while (c.moveToNext());
arrayAdapter.notifyDataSetChanged();
lst1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String tt = titles.get(position).toString();
student stu = stud.get(position);
Intent i = new Intent(getApplicationContext(),edit.class);
i.putExtra("age",stu.age);
startActivity(i);
}
});
You need to create a class for your custom items:
class Student{
String id;
String name;
String age;
String title;
public Student(String id, String name, String age)
{
this.id = id;
this.name = name;
this.age = age;
title = id + " \t" +name+" \t"+age;
}
}
//View.java:
if(c.moveToFirst()) {
do {
Student tmpStudent = new Student(c.getString(id), c.getString(name), c.getString(age));
titles.add(tmpStudent.title);
} while (c.moveToNext());
arrayAdapter.notifyDataSetChanged();
lst1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String studentString[] = titles.get(position).toString().Split(" \t");
Student tmpStringStudent = new Student(studentString[0], studentString[1], studentString[2]);
Intent i = new Intent(getApplicationContext(),edit.class);
i.putExtra("id",tmpStringStudent.id);
i.putExtra("name",tmpStringStudent.name);
i.putExtra("age",tmpStringStudent.age);
startActivity(i);
}
});
}
//Edit.java:
public class edit extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit);
EditText ageEditText = findViewById(R.id.age);
EditText idEditText = findViewById(R.id.id);
EditText nameEditText = findViewById(R.id.name);
Intent i = getIntent();
String id = i.getStringExtra("id").toString();
String name = i.getStringExtra("name").toString();
String age = i.getStringExtra("age").toString();
idEditText.setText(id);
nameEditText.setText(name);
ageEditText.setText(age);
}
}
I hope this helps.

Changing the textview to 2 decimal place in android recyclerview textview

I have a textview in a recyclerview which shows decimal money values saved in an sqlite database. But when I enter $10.00 into the database the recyclerview textview shows it as $10 instead of $10.00. How do I fix this?
This is my layout for the recyclerview:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/pound"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="1"
android:paddingBottom="5dp"
android:paddingTop="5dp"
android:paddingStart="8dp"
android:text="£"
android:textSize="20sp"
android:textColor="#color/fab2_color"/>
<TextView
android:id="#+id/favourite_textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_weight="1"
android:maxLength="9"
android:paddingBottom="5dp"
android:paddingTop="5dp"
android:textSize="20sp"
android:textColor="#color/fab2_color"
/>
</LinearLayout>
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:layout_marginEnd="5dp"
android:layout_marginRight="5dp"
android:color="#ffffff" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="30dp">
<TextView
android:id="#+id/category_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:maxLines="1"
android:paddingBottom="5dp"
android:paddingTop="5dp"
android:paddingStart="8dp"/>
<TextView
android:id="#+id/verse_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_weight="1"
android:gravity="end"
android:maxLines="1"
android:paddingBottom="5dp"
android:paddingTop="5dp" />
</LinearLayout>
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:layout_marginEnd="5dp"
android:layout_marginRight="5dp"
android:color="#ffffff" />
</android.support.v7.widget.CardView>
Here is where I insert the values into the database:
public void AddData(){
FloatingActionButton fab2 = (FloatingActionButton) findViewById(R.id.fab_tick_income);
fab2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
formatter = new DecimalFormat("0.00");
RawincomeValue = editAmountincome.getRawValue();
FormatedincomeVal = (double) RawincomeValue/100;
if (FormatedincomeVal > 0){
isAmountInserted = true;
}
else{
isAmountInserted = false;
}
noteCheck = editNotesincome.getText().toString().trim();
if(noteCheck.isEmpty())
{
noteCheck = noteCheck.replace("", "No Note Inserted");
}
else
{
//EditText is not empty
}
if(isCategoryInserted && isDateInserted && isAmountInserted && isAccountInserted) {
myDbincome.insertincomeData(
FormatedincomeVal,
editDateincome.getText().toString(),
noteCheck,
category,
account);
Toast.makeText(add_income.this,"Income Registered",Toast.LENGTH_LONG).show();
Intent intent=new Intent(add_income.this, MainActivity.class);
startActivity(intent);
}
adapter viewholder as per request:
public class IncomeAdapter extends RecyclerView.Adapter<IncomeAdapter.ViewHolder> {
private final ArrayList<String> dataSet;
private final ArrayList<String> dataSet2;
private final ArrayList<String> dataSet3;
private ItemClickListener clickListener;
DecimalFormat formatter = new DecimalFormat("0.00");
String myListPreference;
Context ctx;
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
final TextView pound;
final TextView mTextView;
final TextView textView;
final TextView categoryText;
final CardView cardView;
ViewHolder(View v) {
super(v);
SharedPreferences sharedPreferences = android.support.v7.preference.PreferenceManager.getDefaultSharedPreferences(ctx);
myListPreference = sharedPreferences.getString("CurrencyType", "£");
pound = (TextView) v.findViewById(R.id.pound);
mTextView = (TextView) v.findViewById(R.id.favourite_textView);
categoryText = (TextView) v.findViewById(R.id.category_text);
textView = (TextView) v.findViewById(R.id.verse_text);
cardView = (CardView) v.findViewById(R.id.cardview);
pound.setText(""+ myListPreference);
v.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (clickListener != null) clickListener.onClick(view, getAdapterPosition());
}
}
public IncomeAdapter(ArrayList<String> myDataset, ArrayList<String> myDataSet2, ArrayList<String> myDataset3, Context ctx) {
this.dataSet = myDataset;
this.dataSet2 = myDataSet2;
this.dataSet3 = myDataset3;
this.ctx = ctx;
}
How I put the information into the recyclerview:
private void populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
ArrayList<String> arrayList = new ArrayList<>();
ArrayList<String> arrayList2 = new ArrayList<>();
ArrayList<String> arrayList3 = new ArrayList<>();
IncomeAdapter incomeAdapter = new IncomeAdapter(arrayList,arrayList2,arrayList3, getContext());
mListView.setAdapter(incomeAdapter);
incomeAdapter.setClickListener(this);
incomedata = mDatabaseHelper.getincomeData();
if(incomedata.moveToFirst()){
do {
arrayList.add(incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_AMOUNT)));
arrayList2.add(incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_DATE)));
arrayList3.add(incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_CATEGORY)));
}
while (incomedata.moveToNext());
}
incomeAdapter.notifyDataSetChanged();
}
textview.setText( String.format( "Value
of a: %.2f", a ) );

Circular imageview dissappears in listview after fling

Im generating a feed full of images (similar to instagram post) using Glide for loading images and user's profile picture. After i get the data from server, i load the Url's of images inside the listitem. Initally All items are being loaded properly.
The issue is that when i fast scroll the listview, user profile picture dissappears and that view doesnt respond to onClick Events. Please explain why this happens and how can i resolve this?
XML layout of each list Item.
<?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:layout_marginBottom="20dp"
android:orientation="vertical" >
<RelativeLayout android:id="#+id/userheader"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="10dp"
android:layout_weight="1">
<com.mikhaellopez.circularimageview.CircularImageView
android:id="#+id/realdp"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="#drawable/nodp"
android:scaleType="centerCrop"
android:adjustViewBounds="true"/>
<TextView
android:id="#+id/handle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/realdp"
android:text="handle"
android:layout_marginLeft="3dp"
android:gravity="center_vertical"
android:layout_alignTop="#+id/realdp"
android:layout_alignBottom="#+id/realdp"
android:textAppearance="?android:attr/textAppearanceMedium"/>
<TextView
android:id="#+id/uploadtime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/handle"
android:layout_marginRight="5dp"
android:layout_alignParentRight="true"
android:text="time"
android:textAppearance="?android:attr/textAppearanceSmall" />
<RelativeLayout android:id="#+id/rlimg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/handle">
<ImageView
android:id="#+id/imgpost"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:adjustViewBounds="true"
android:background="#ffffff"/>
</RelativeLayout>
<RelativeLayout android:id="#+id/bottom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/rlimg"
android:layout_marginTop="5dp">
<com.sivaram.fishograph.FlipImageView
android:id="#+id/like"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#00000000"
android:layout_marginLeft="20dp"
android:src="#drawable/hook_unlike"/>
<ImageButton
android:id="#+id/comment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#00000000"
android:layout_toRightOf="#+id/likesnum"
android:layout_marginLeft="20dp"
android:src="#drawable/comment" />
<ImageButton
android:id="#+id/more"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="3dp"
android:layout_alignParentRight="true"
android:background="#00000000"
android:src="#drawable/more" />
<TextView
android:id="#+id/likesnum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/like"
android:layout_alignTop="#+id/like"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/like"
android:text="likes"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#440011" />
<TextView
android:id="#+id/comnum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/comment"
android:layout_alignTop="#+id/comment"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#+id/comment"
android:gravity="center_vertical"
android:text="comments"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#440011" />
</RelativeLayout>
</RelativeLayout>
<TextView
android:id="#+id/caption"
android:layout_width="match_parent"
android:layout_height="0dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_below="#+id/userheader"
android:gravity="center_horizontal"
android:layout_weight="1"
android:text="Caption"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/dummy"
android:layout_width="match_parent"
android:layout_height="0dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_below="#+id/caption"
android:gravity="center_horizontal"
android:layout_weight="1"
android:text=""
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
Java Code for generating feed:
public class Feed extends Fragment implements OnScrollListener
{
String handle;
ListView lvposts;
Jsparser jp;
int width,height;
int maxMemory;
int currentFirstVisibleItem ;
int currentVisibleItemCount;
PostAdapter pa;
ArrayList<eachpost> posts;
int value = 1;
boolean isLoading = false;
int photoid;
private List<String> myData;
Boolean tapped = false, Loading= false;
SharedPreferences spf;
ArrayList<String> likes;
public Feed()
{
super();
}
Feed(String handle)
{
super();
photoid = 99999999;
this.handle = handle;
}
#Override
public void onCreate(Bundle b)
{
super.onCreate(b);
maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
spf = getActivity().getSharedPreferences("prefs",Context.MODE_PRIVATE);
likes = new ArrayList<String>();
}
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup vg, Bundle b)
{
View v = inflater.inflate(R.layout.allposts, vg, false);
ActionBar ab = ((ActionBarActivity) getActivity()).getSupportActionBar();
ab.setBackgroundDrawable(new ColorDrawable(Color.RED));
ab.hide();
lvposts = (ListView) v.findViewById(R.id.lvposts);
jp = new Jsparser();
Display d = getActivity().getWindowManager().getDefaultDisplay();
width = d.getWidth();
height = d.getHeight();
lvposts.setOnScrollListener(this);
posts = new ArrayList<eachpost>();
pa = new PostAdapter(getActivity(),R.layout.postcontent,posts,inflater);
Loading = true;
lvposts.setAdapter(pa);
new GetData(photoid).execute();
return v;
}
class GetData extends AsyncTask<String,String,String>
{
String msg;
Integer limit,success=0;
ProgressDialog pd;
Bitmap dpbm;
GetData(int l)
{
limit = l;
}
#Override
public void onPreExecute()
{
}
#Override
protected String doInBackground(String... params) {
List<NameValuePair> lp = new ArrayList<NameValuePair>();
lp.add(new BasicNameValuePair("handle",handle));
lp.add(new BasicNameValuePair("photoid",limit.toString()));
JSONObject job = jp.makeHttpRequest("server/getfeed.php", "POST", lp);
try
{
Log.d("json", job.toString());
success = job.getInt("success");
msg = job.getString("message");
if(success==1)
{
JSONArray ja = job.getJSONArray("posts");
for(int c = 0; c<ja.length(); c++)
{
JSONObject jb = ja.getJSONObject(c);
posts.add(new eachpost(jb.getString("handle"),jb.getString("url"), jb.getString("caption"),
jb.getString("uldatetime"), jb.getInt("likescount"), jb.getInt("comcount"), jb.getString("dpurl"), jb.getInt("isliked"),jb.getInt("photoid") ));
}
}
else
{
}
}
catch(Exception e)
{
e.printStackTrace();
}
return msg;
}
#Override
public void onPostExecute(String url)
{
Loading = false;
if(success==1)
{
photoid = posts.get(posts.size()-1).getPhotoid();
Log.d("last id",photoid+"");
Log.d("Length of posts",""+posts.size());
pa.notifyDataSetChanged();
}
}
}
class PostAdapter extends ArrayAdapter<eachpost>
{
ViewHolder vholder;
String root = Environment.getExternalStorageDirectory().toString();
File dir = new File (root + ".feed");
Map<Integer,View> myViews;
public PostAdapter(Context context, int resource, ArrayList<eachpost> list, LayoutInflater li) {
super(context, R.layout.postcontent, list);
myViews = new HashMap<Integer,View>();
}
#Override
public View getView(final int pos,View v,ViewGroup vg)
{
final eachpost post = posts.get(pos);
final String imgurl = post.getPhotoUrl();
String dpurl = post.getDpurl();
int isliked = post.getIsliked();
View row = myViews.get(pos);
if(row == null)
{
row = getActivity().getLayoutInflater().inflate(R.layout.postcontent,vg,false);
row.setMinimumHeight(height);
vholder = new ViewHolder();
vholder.handle = ((TextView) row.findViewById(R.id.handle));
vholder.caption = ((TextView) row.findViewById(R.id.caption));
vholder.likesnum = ((TextView) row.findViewById(R.id.likesnum));
vholder.comnum = ((TextView) row.findViewById(R.id.comnum));
vholder.uploadtime = ((TextView) row.findViewById(R.id.uploadtime));
vholder.photo = (ImageView) row.findViewById(R.id.imgpost);
vholder.feeddp = (CircularImageView) row.findViewById(R.id.realdp);
vholder.like = (FlipImageView) row.findViewById(R.id.like);
LayoutParams lp = vholder.photo.getLayoutParams();
lp.width = width;
lp.height = width;
vholder.handle.setText(post.getHandle());
vholder.caption.setText(post.getCaption());
vholder.likesnum.setText(post.getLikes()+"");
vholder.comnum.setText(post.getComments()+"");
vholder.uploadtime.setText(post.getUl());
Drawable d = getResources().getDrawable(R.drawable.hook_like);
vholder.like.setFlippedDrawable(d);
Glide.with(getActivity()).load("server/"+imgurl).into(vholder.photo);
if(dpurl.contains("http"))
Glide.with(getActivity()).load(dpurl).into(vholder.feeddp);
else
Glide.with(getActivity()).load("server/"+dpurl).into(vholder.feeddp);
Log.d("image loading", dpurl + "-" + imgurl);
if(isliked==1)
{
vholder.like.setFlipped(true,false);
likes.add(imgurl);
}
vholder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View temp = myViews.get(pos);
final FlipImageView like = (FlipImageView) temp.findViewById(R.id.like);
final TextView likesnum = (TextView) temp.findViewById(R.id.likesnum);
like.toggleFlip();
if(!likes.contains(imgurl))
{
posts.get(pos).incrementLikes(handle);
likes.add(posts.get(pos).getPhotoUrl());
likesnum.setText(posts.get(pos).getLikes()+"");
}
else
{
likes.remove(posts.get(pos).getPhotoUrl());
posts.get(pos).decrementLikes(handle);
likesnum.setText(posts.get(pos).getLikes()+"");
}
}
});
row.setTag(vholder);
myViews.put(pos, row);
}
return row;
}
#Override
public boolean isEnabled(int position)
{
return true;
}
} //end of adapter class
static class ViewHolder {
TextView handle;
TextView caption;
TextView likesnum;
TextView comnum;
TextView uploadtime;
ImageView photo;
CircularImageView feeddp;
FlipImageView like;
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (this.currentVisibleItemCount > 0 && scrollState == SCROLL_STATE_FLING) {
/*** In this way I detect if there's been a scroll which has completed ***/
/*** do the work for load more date! ***/
if(currentFirstVisibleItem > (currentVisibleItemCount - 2) && Loading!=true)
{
new GetData(photoid).execute();
}
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
this.currentFirstVisibleItem = firstVisibleItem;
this.currentVisibleItemCount = visibleItemCount;
}
}
When loading multiple images there is always caching problem when using Async Tasks. I recommend an open source library Picasso. It will load the images and cache it. After that most probably, your fast scroll problem will solve.
The cause can also be the size of the images being received. Picasso has methods by which you can resize the image before putting it onto the image view
try with this modified getView
#Override
public View getView(final int pos,View v,ViewGroup vg)
{
final eachpost post = posts.get(pos);
final String imgurl = post.getPhotoUrl();
String dpurl = post.getDpurl();
int isliked = post.getIsliked();
View row = myViews.get(pos);
if(row == null)
{
row = getActivity().getLayoutInflater().inflate(R.layout.postcontent,vg,false);
row.setMinimumHeight(height);
vholder = new ViewHolder();
vholder.handle = ((TextView) row.findViewById(R.id.handle));
vholder.caption = ((TextView) row.findViewById(R.id.caption));
vholder.likesnum = ((TextView) row.findViewById(R.id.likesnum));
vholder.comnum = ((TextView) row.findViewById(R.id.comnum));
vholder.uploadtime = ((TextView) row.findViewById(R.id.uploadtime));
vholder.photo = (ImageView) row.findViewById(R.id.imgpost);
vholder.feeddp = (CircularImageView) row.findViewById(R.id.realdp);
vholder.like = (FlipImageView) row.findViewById(R.id.like);
LayoutParams lp = vholder.photo.getLayoutParams();
lp.width = width;
lp.height = width;
row.setTag(vholder); //changed here setTag()
}else{
vholder=(ViewHolder)row.getTag(); //changed here getTag()
}
vholder.handle.setText(post.getHandle());
vholder.caption.setText(post.getCaption());
vholder.likesnum.setText(post.getLikes()+"");
vholder.comnum.setText(post.getComments()+"");
vholder.uploadtime.setText(post.getUl());
Drawable d = getResources().getDrawable(R.drawable.hook_like);
vholder.like.setFlippedDrawable(d);
Glide.with(getActivity()).load("server/"+imgurl).into(vholder.photo);
if(dpurl.contains("http"))
Glide.with(getActivity()).load(dpurl).into(vholder.feeddp);
else
Glide.with(getActivity()).load("server/"+dpurl).into(vholder.feeddp);
Log.d("image loading", dpurl + "-" + imgurl);
if(isliked==1)
{
vholder.like.setFlipped(true,false);
likes.add(imgurl);
}
vholder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View temp = myViews.get(pos);
final FlipImageView like = (FlipImageView) temp.findViewById(R.id.like);
final TextView likesnum = (TextView) temp.findViewById(R.id.likesnum);
like.toggleFlip();
if(!likes.contains(imgurl))
{
posts.get(pos).incrementLikes(handle);
likes.add(posts.get(pos).getPhotoUrl());
likesnum.setText(posts.get(pos).getLikes()+"");
}
else
{
likes.remove(posts.get(pos).getPhotoUrl());
posts.get(pos).decrementLikes(handle);
likesnum.setText(posts.get(pos).getLikes()+"");
}
}
});
myViews.put(pos, row);
}
return row;
}

TextView crash?

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;
}
}

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