Android Layout help needed - android

I am having difficulty making my layout to work...
What I want to do is have two spinners and a button below those and once the button is clicked, I display the results based on the values selected in the spinners.
-----------
| Spinner 1 |
-----------
-----------
| Spinner 2 |
-----------
-----------
| Button |
-----------
Result 1
Result 2
Result 3
Result 4
Result 5
I have tried to put the results in a ListView, but the problem I face is that once the button is clicked, I can see the repetition of Spinner1, Spinner2 and the Button itself multiple times.
The xml for the layout is as follows:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/country_arrays"
android:prompt="#string/country_prompt" />
<Spinner
android:id="#+id/spinner2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/country_arrays"
android:prompt="#string/country_prompt" />
<Button
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/done" />
<LinearLayout
android:id="#+id/moreContent"
android:layout_width="match_parent"
android:visibility="visible"
android:orientation="vertical"
android:layout_height="wrap_content"
>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
android:textColor="#ff0000"
android:textSize="12sp" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:contentDescription="#string/hello_world"
android:gravity="center_vertical"
android:text="#string/hello_world"
android:textColor="#0000ff"
android:textSize="12sp" />
</LinearLayout>
Can someone please advise where am I going wrong?
The code is as follows:
package ms.timetable;
import java.io.FileNotFoundException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import java.util.Map.Entry;
import android.os.AsyncTask;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends ListActivity {
final Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void addListenerOnButton() {
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
RetreiveFeedTask rft = new RetreiveFeedTask();
rft.execute();
}
});
}
#SuppressLint("NewApi")
private class RetreiveFeedTask extends AsyncTask<Void, Void, String> {
TreeMap<String, String> _timetable = null;
#Override
protected String doInBackground(Void... arg0) {
// TODO Auto-generated method stub
_timetable = FetchTimetableInfo();
return null;
}
protected void onPostExecute(String str){
if (_timetable != null){
ArrayList<TimeTable> tarr = new ArrayList<TimeTable>();
Iterator<Entry<String, String>> it = _timetable.entrySet().iterator();
String toastText = "";
while (it.hasNext())
{
Map.Entry<String, String> pairs = (Map.Entry<String, String>)it.next();
String key = pairs.getKey();
String value = pairs.getValue();
toastText = toastText + key + " --- " + value + "\n";
//System.err.println(key + " --- " + value);
TimeTable tt = new TimeTable();
tt.set_line(value);
String [] tem = key.split("---");
tt.set_arrival(tem[1]);
tt.set_departure(tem[1]);
tarr.add(tt);
}
//Toast.makeText(context, toastText, Toast.LENGTH_LONG).show();
//tmap.add(_timetable);
setListAdapter((ListAdapter) new TimetableAdapter(getApplicationContext(), tarr));
}
}
private TreeMap<String, String> FetchTimetableInfo(){
Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
Spinner spinner2 = (Spinner) findViewById(R.id.spinner2);
String origin = (String) spinner1.getSelectedItem();
String destination = (String) spinner2.getSelectedItem();
//String val = String.valueOf(spinner1.getSelectedItem());
ArrayList<String> linesServOrigin = LineStation.GetServingLines(origin);
ArrayList<String> linesServDest = LineStation.GetServingLines(destination);
linesServOrigin.retainAll(linesServDest);
//ArrayList<String> preferredLines = linesServOrigin.re.retainAll(linesServDest);
Log.e(this.getClass().toString(), "Selected value is : " + linesServOrigin.get(0));
try
{
for (int k = 0; k < linesServOrigin.size(); k++)
{
String url = "http://tt.ptv.vic.gov.au/tt/XSLT_REQUEST?itdLPxx_lineMain=" + LineStation.GetLineMain(linesServOrigin.get(0)) + "&itdLPxx_lineID=" + LineStation.GetLineID(linesServOrigin.get(0)) + "&itdLPxx_output=html";
DataManager dm = new DataManager(url, getApplicationContext());
ArrayList<String> stationData = dm.GetStationsData();
ArrayList<ArrayList<String>> timetableData = dm.GetTimetableData();
ArrayList<String> originTimetable = null;
ArrayList<String> originTimetable1 = null;
ArrayList<String> destinationTimetable = null;
ArrayList<String> destinationTimetable1 = null;
int origPos = 0;
int destPos = 0;
int ctr = 0;
for (int i = 0; i < stationData.size(); i++)
{
if (stationData.get(i).equals(origin) || (origin + " - DEP").equals(stationData.get(i)))
{
//originTimetable = timetableData[i];
origPos = i;
}
else if (stationData.get(i).equals( destination) || (destination + " - ARR").equals(stationData.get(i)))
{
//destinationTimetable = timetableData[i];
destPos = i;
}
if (origPos != 0 && destPos != 0)
{
break;
}
}
if (origPos > destPos)
{
dm.SwitchDirection();
stationData = dm.GetStationsData();
timetableData = dm.GetTimetableData();
}
for (int i = stationData.size() - 1; i >= 0; i--)
{
if (stationData.get(i).equals(origin) || (origin + " - DEP").equals(stationData.get(i)))
{
if (originTimetable == null)
{
originTimetable = timetableData.get(i);
}
else if (originTimetable1 == null)
{
originTimetable1 = timetableData.get(i);
}
}
else if (stationData.get(i).equals(destination) || (destination + " - ARR").equals(stationData.get(i)))
{
if (destinationTimetable == null)
{
destinationTimetable = timetableData.get(i);
}
else if (destinationTimetable1 == null)
{
destinationTimetable1 = timetableData.get(i);
}
}
}
TreeMap<String, String> ttable = new TreeMap<String, String>();
if (originTimetable != null && destinationTimetable != null)
{
//int curtime = Integer.parseInt(DateTime.Now.ToString("HHmm", CultureInfo.CurrentCulture));
String temp = new SimpleDateFormat("HHmm").format(Calendar.getInstance().getTime());
int curtime =Integer.parseInt(temp);
System.err.println("Origin timetable size = " + originTimetable.size());
System.err.println("Destination timetable size = " + destinationTimetable.size());
for (int j = 0; j < originTimetable.size(); j++)
{
if (Integer.parseInt((originTimetable.get(j))) > curtime)
{
if (Integer.parseInt((destinationTimetable.get(j))) == -1)
{
if (destinationTimetable1 == null || (Integer.parseInt(destinationTimetable1.get(j)) == -1))
{
continue;
}
}
else if (destinationTimetable1 != null && Integer.parseInt(destinationTimetable1.get(j)) == -1)
{
if (destinationTimetable == null || (Integer.parseInt(destinationTimetable.get(j)) == -1))
{
continue;
}
}
ctr++;
if (destinationTimetable1 != null)
{
if (Integer.parseInt(originTimetable.get(j)) < Integer.parseInt(destinationTimetable1.get(j)))
{
ttable.put(originTimetable.get(j) + " --- " + destinationTimetable1.get(j), linesServOrigin.get(k));
}
}
else
{
if (Integer.parseInt(originTimetable.get(j)) < Integer.parseInt(destinationTimetable.get(j)))
{
ttable.put(originTimetable.get(j) + " --- " + destinationTimetable.get(j), linesServOrigin.get(k));
}
}
if (ctr == 5)
{
break;
}
}
}
ctr = 0;
if (originTimetable1 != null)
{
for (int j = 0; j < originTimetable1.size(); j++)
{
if (originTimetable1 != null && Integer.parseInt(originTimetable1.get(j)) > curtime)
{
if (Integer.parseInt(destinationTimetable.get(j)) == -1)
{
if (destinationTimetable1 == null || (Integer.parseInt(destinationTimetable1.get(j)) == -1))
{
continue;
}
}
else if (destinationTimetable1 != null && Integer.parseInt(destinationTimetable1.get(j)) == -1)
{
if (destinationTimetable == null || (Integer.parseInt(destinationTimetable.get(j))) == -1)
{
continue;
}
}
ctr++;
if (destinationTimetable1 != null)
{
if (Integer.parseInt(originTimetable1.get(j)) < Integer.parseInt(destinationTimetable1.get(j)))
{
ttable.put(originTimetable1.get(j) + " --- " + destinationTimetable1.get(j), linesServOrigin.get(k));
}
}
else
{
if (Integer.parseInt(originTimetable1.get(j)) < Integer.parseInt(destinationTimetable.get(j)))
{
ttable.put(originTimetable1.get(j) + " --- " + destinationTimetable.get(j), linesServOrigin.get(k));
}
}
if (ctr == 5)
{
break;
}
}
}
}
Iterator<Entry<String, String>> it = ttable.entrySet().iterator();
//foreach (KeyValuePair<String, List<String>> item in lineStations)
while (it.hasNext())
{
Map.Entry<String, String> pairs = (Map.Entry<String, String>)it.next();
String key = pairs.getKey();
String value = pairs.getValue();
System.err.println(key + " --- " + value);
}
return ttable;
}
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
class TimeTable{
private String _departure, _arrival, _line;
public TimeTable(){
}
public TimeTable(String departure, String arrival, String line){
_departure = departure;
_arrival = arrival;
_line = line;
}
public String get_departure() {
return _departure;
}
public void set_departure(String _departure) {
this._departure = _departure;
}
public String get_arrival() {
return _arrival;
}
public void set_arrival(String _arrival) {
this._arrival = _arrival;
}
public String get_line() {
return _line;
}
public void set_line(String _line) {
this._line = _line;
}
}
}
The adapter is as follows:
package ms.timetable;
import java.util.ArrayList;
import ms.timetable.MainActivity.TimeTable;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class TimetableAdapter extends ArrayAdapter<TimeTable>{
private final Context context;
private final ArrayList<TimeTable> values;
public TimetableAdapter(Context context, ArrayList<TimeTable> values){
super(context, R.layout.activity_main, values);
this.context = context;
this.values = values;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.activity_main, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.textView1);
TextView textView2 = (TextView) rowView.findViewById(R.id.textView2);
//System.err.println("Position is : "+position);
TimeTable tt = values.get(position);
textView.setText(tt.get_departure());
textView2.setText(tt.get_arrival());
return rowView;
}
}

The problem is due to
View rowView = inflater.inflate(R.layout.activity_main, parent, false);
in getView() method.
You are inflating whole activity_main in a row and then adding it to a listview.
Put a row for results in separate xml instead of activity_main. So you will have a new xml file say, row.xml which will contain:
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
android:textColor="#ff0000"
android:textSize="12sp" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:contentDescription="#string/hello_world"
android:gravity="center_vertical"
android:text="#string/hello_world"
android:textColor="#0000ff"
android:textSize="12sp" />
So you will have to inflate as
View rowView = inflater.inflate(R.layout.row, parent, false);
And then add the generated rows in the listview which is in activity_main.xml.
So your problem will be solved. Hope it helps.

Related

rotating text,marquee is not appropriate

I have added this code to my MainActivity.java:
tv6.setText("11111111111\n"+strPokus2+"\nA\n"+strPokus+"\nB");
tv6.setSingleLine(true);
tv6.setMarqueeRepeatLimit(-1);
tv6.setEllipsize(TextUtils.TruncateAt.MARQUEE);
tv6.setSelected(true);
HOWEVER, the text is still static, not rotating/moving. What's wrong ??
HERE IS MainActivity.java and activity_main.xml below it:
package com.example.tablelayout6;
import androidx.appcompat.app.AppCompatActivity;
import android.icu.text.MeasureFormat;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TableRow;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.TableLayout;
import android.text.TextUtils;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import java.lang.StringBuilder;
public class MainActivity extends AppCompatActivity {
public boolean g=true;
public Integer N=1;
public String a="2";
private EditText editText1;
private EditText linear;
private Integer[] hodnoty =new Integer[10];
private String[] koal=new String[10];
private float[] shap=new float[10];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public boolean iswinning(Integer J,int ii) {
return true;
}
public Integer fact (Integer f) {
if (f==0) return 1;
else return f*fact((Integer) (f-1));
}
//T pocetHracu
public Integer[] stringToArray(String binary) {
Integer[] arrayOfPLayers=new Integer[binary.length()];
for(int i=0;i<binary.length();i++) {
arrayOfPLayers[i]=Integer.parseInt("" + binary.charAt(i));
}
return arrayOfPLayers;
}
//N je pocet koalici
public void click5(View view) {
int pocetHracu=Integer.toBinaryString(N-1).length();
Integer[][] koalice=new Integer[N][pocetHracu];
Integer[][] koalice2=new Integer[N][pocetHracu];
Integer[][] koalice3=new Integer[N][pocetHracu];
TextView tv6 = (TextView) findViewById(R.id.textView6);
for (Integer ith=0;ith<N;ith++) {
for(Integer T=0;T<pocetHracu;T++) {
String StringPadded=stf(Integer.toBinaryString(ith),pocetHracu-Integer.toBinaryString(ith).length());
koalice[ith][T]=stringToArray(StringPadded)[T];
koalice2[ith][T]=stringToArray(StringPadded)[T];
koalice3[ith][T]=stringToArray(StringPadded)[T];
}
}
float[] shap=new float[pocetHracu];
float[] vyhryKoalici = new float[N];
Integer[] isSwing=new Integer[pocetHracu];
for (int i=0; i<N;i++) {
editText1 = (EditText) findViewById(330+i);
String a=editText1.getText().toString();
float f1 = Float.parseFloat(a);
vyhryKoalici[i]=f1;
}
Integer[] kolikJeSwingu= new Integer[pocetHracu];
String S="";
String kde="j";
Integer jth;
for (int p = 0; p < pocetHracu; p++) {
isSwing[p] =0;
kolikJeSwingu[p]=N;
}
// Integer swingove2=pocetHracu*N;
Integer bool=1;
Integer canBanzhaf=1;
for(Integer contr=0;contr<N;contr++)
{
if(vyhryKoalici[contr]!=0 && vyhryKoalici[contr]!=1) {
canBanzhaf=0;
}
}
for(Integer T=0;T<pocetHracu;T++) {
for (Integer ith = 0; ith < N; ith++) {
bool = 1;
//vyhryKoalici[ith];
//musis najit jth<N pro ktere koalice3[jth]=S-ith
if ((koalice[ith][T] == 1) && (vyhryKoalici[ith]==1)) {
koalice3[ith][T] = 0;
for (jth = 0; jth < N; jth++) {
for (Integer k = 0; k < pocetHracu; k++)
{
//if (k != T && koalice[ith][k] != koalice3[jth][k]) {
if ((k != T) && (koalice[ith][k] != koalice3[jth][k])) {
bool = 0;
// swingove2--;
kde+="\nk"+k.toString()+"T"+T.toString()+">";
}
}
kde+="\njth"+jth.toString()+"ith"+ith.toString()+"T"+T.toString();
//(vyhryKoalici[jth]
if ((vyhryKoalici[jth]==0) && (bool == 1)) {
isSwing[T]++;
}
bool=1;
}
koalice3[ith][T]=1;
bool=1;
}
}
}
//kolikJeSwingu(Integer TmaSwing, Integer pocetHracu, Integer pocetKoalici,
// Integer[][] koal, Integer[] koalicePriKtereJeSwing, float[] vyhryKoal)
for (Integer ith = 0; ith < N; ith++) {
for(Integer T=0;T<pocetHracu;T++) {
//isSwingBool(Integer kteraKoalice, Integer TmaSwing, Integer pocetHracu, Integer pocetKoalici,
// Integer[][] koal, Integer[] koalicePriKtereJeSwing, float[] vyhryKoal) {
// kolikJeSwingu[T]+=kolikJeSwingu(T, pocetHracu, N,
// koalice, koalice[ith],vyhryKoalici);
if (koalice[ith][T] == 1) {
koalice2[ith][T] = 0;
for (jth = 0; jth < N; jth++) {
bool = 1;
for (int k = 0; k < pocetHracu; k++) {
if (k != T && koalice[ith][k] != koalice2[jth][k]) {
bool = 0;
}
}
int bool2=0;
koalice2[ith][T] = 1;
if (vyhryKoalici[ith] == 1 && vyhryKoalici[jth] == 0) {
for (int k = 0; k < pocetHracu; k++) {
if (koalice[ith][k] != koalice2[jth][k]) {
bool2++;
}
}
// if(bool2==1) {
// isSwing[T]++;
// }
}
koalice2[ith][T] = 1;
Integer t = 0;
for (int p = 0; p < pocetHracu; p++) {
t += koalice[ith][p];
}
// Integer[] isSwing=new Integer[pocetHracu];
if (bool == 1) {
shap[T] += (float) ((float) fact(t - 1) * fact(pocetHracu - t) / (float) (fact(pocetHracu)) * (float) (vyhryKoalici[ith] - vyhryKoalici[jth]));
}
}
}
}
}
S+="here";
String T2="";
T2+="banzhaf";
Integer swingove=0;
for(int p=0;p<pocetHracu;p++) {
swingove+=isSwing[p];
}
String strPokus="";
if(canBanzhaf==1) {
strPokus = "banzhaf ";
} else {
strPokus="banzhaf err ";
}
float[] banzh=new float[pocetHracu];
for(int p=0;p<pocetHracu;p++)
{
banzh[p]=(float) isSwing[p]/(float) swingove;
}
String strPokus2="shap ";
for(int i=0;i<pocetHracu;i++) {
// S+=(" "+String.valueOf(shap[i]));
strPokus2+=String.format("%.2f ",shap[i]);
strPokus+=String.format("%.2f ",banzh[i]);
}
// tv6.setText(strPokus2+"\n"+strPokus+"\nswing"+isSwing[0]+"swingPrvni:"+isSwing[1]+"\nH"+swingove);
tv6.setText("11111111111\n"+strPokus2+"\nA\n"+strPokus+"\nB");
tv6.setSingleLine(true);
tv6.setMarqueeRepeatLimit(-1);
tv6.setEllipsize(TextUtils.TruncateAt.MARQUEE);
tv6.setSelected(true);
// TextView textView=(TextView)findViewById(R.id.text_test);
/* tv6.setEllipsize(TextUtils.TruncateAt.MARQUEE);
tv6.setSingleLine(true);
tv6.setMarqueeRepeatLimit(-1);
tv6.setFocusableInTouchMode(true);
tv6.setFocusable(true);
*/
/* TextView txt = new TextView(this);
txt.setText("This is the infinite marquee");
txt.setEllipsize(TextUtils.TruncateAt.MARQUEE);
txt.setSingleLine(true);
txt.setMarqueeRepeatLimit(-1);
txt.setSelected(true);
*/
}
public void click4(View view) {
//
if (g) {
linear = (EditText) findViewById(R.id.simpleEditText);
if (N == 1) {
linear.setText("1");
}
String a = linear.getText().toString();
N = Integer.parseInt(a);
N++;
linear.setText(N.toString());
}
}
public void click7(View view) {
if (g) {
//
linear = (EditText) findViewById(R.id.simpleEditText);
if (N == 0 || N == 1) {
linear.setText("1");
}
String a = linear.getText().toString();
N = Integer.parseInt(a);
if (N > 1) N--;
linear.setText(N.toString());
}
}
public String stf(String a,Integer l) {
if(l==0) { return a; }
l--;
return stf("0"+a,l);
}
public void click2(View view) {
if (g) {
g = false;
String col1;
String col2;
// String playerChanged;
TableLayout tl = (TableLayout) findViewById(R.id.tableLayout1);
EditText editText = (EditText) findViewById(R.id.simpleEditText);
TableRow row = new TableRow(this);
TextView tv = new TextView(this);
TextView c = new TextView(this);
//EditText etUserInfoNewValue = (EditText)findViewById(R.id.simpleEditText);
// a = editText.getText().toString();
tv.setId(202);
tv.setText("This is text");
//
tl.addView(row);
row.addView(tv);
int sf = Integer.toBinaryString(N - 1).length();
for (int x = 0; x < N; x++) {
//String.format("%010d",(
String jl = Integer.toBinaryString(x);
String jl2 = stf(jl, sf - jl.length());
//koal[x]=jl2;
col1 = "(" + x + ")" + jl2;
// col1 = "(" + x + ")"+Integer.toBinaryString(x);
col2 = "1";
//col3 = "(" + x + ") Column 3";
//col4 = "(" + x + ") Column 4";
TableRow newRow = new TableRow(this);
TextView column1 = new TextView(this);
TextView column2 = new TextView(this);
EditText editText1 = new EditText(this);
editText1.setId(330 + x);
// String stringAnswer = editText1.getText().toString();
TextView column3 = new TextView(this);
// TextView column4 = new TextView(this);
editText1.setText("0 ");
column1.setText(col1);
column1.setText(col1);
column2.setText(col2);
//column3.setText(col3);
//column4.setText(col4);
// column1.setText(stringAnswer);
newRow.addView(column1);
newRow.addView(editText1);
newRow.addView(column3);
// newRow.addView(column4);
tl.addView(newRow, new TableLayout.LayoutParams());
}
}
}
}
XML XML XML XML:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="bottom|fill_horizontal"
android:layout_span="#integer/material_motion_duration_long_2"
android:background="#FFFFFF"
android:backgroundTint="#FFFFFF"
android:backgroundTintMode="multiply"
android:foregroundGravity="fill_horizontal|center_horizontal"
android:foregroundTint="#color/purple_200"
android:foregroundTintMode="multiply"
android:requiresFadingEdge="vertical"
android:scrollbarDefaultDelayBeforeFade="10"
android:visibility="visible">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_columnSpan="4"
android:layout_columnWeight="12"
android:accessibilityLiveRegion="none"
android:orientation="vertical">
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="fill_parent"
android:layout_height="match_parent"></TableLayout>
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="#1DE9B6"
android:onClick="click2"
android:text="Generate"
android:textColor="#000000"
android:textSize="10dp" />
<EditText
android:id="#+id/simpleEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:digits="10"
android:hint="Number of coalitions appear here"
android:inputType="text"
android:minHeight="48dp"
android:textColor="#FF0000" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_columnSpan="12"
android:layout_columnWeight="12"
android:accessibilityLiveRegion="none"
android:inputType="textCapCharacters"
android:orientation="horizontal">
<Button
android:id="#+id/button4"
android:layout_width="25mm"
android:layout_height="wrap_content"
android:foregroundTint="#FF0000"
android:foregroundTintMode="src_over"
android:onClick="click4"
android:scrollbarDefaultDelayBeforeFade="4"
android:text="Increase"
android:textSize="11dp" />
<Button
android:id="#+id/button7"
android:layout_width="25mm"
android:layout_height="wrap_content"
android:foregroundTint="#FF0000"
android:foregroundTintMode="src_over"
android:onClick="click7"
android:scrollbarDefaultDelayBeforeFade="4"
android:text="Decrease"
android:textSize="11dp" />
</LinearLayout>
<Button
android:id="#+id/button5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#00E5FF"
android:backgroundTintMode="add"
android:onClick="click5"
android:text="Power indices" />
<TextView
android:id="#+id/textView6"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:text="Shapley and Banzhaf" />
</LinearLayout>
</ScrollView>
EDIT
<TextView
android:id="#+id/tvMarque"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:layout_gravity="center_horizontal"
android:fadingEdge="horizontal"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:padding="5dp"
android:textSize="16sp"
android:text="AHA"
android:visibility="visible" />

while retreiving contacts again on onResume, last contact is re-added on first card in recycler view

I do not understand why last contact is added to the first card in recyclerview again when activity is resumed. I know that it is to do with cursor or content resolver.
Here is the java class with which I have problem.
while retreiving contacts again on onResume, last contact is re-added on first card in recycler view
package com.android.eventers;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.ContactsContract;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberType;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
import java.util.ArrayList;
import java.util.Locale;
public class ContactsActivity extends AppCompatActivity implements ContactsAdapter.ListItemClickListener {
private static final int CHECK_CLICK = 1;
private static final String LIST_STATE_KEY = "list_state";
FloatingActionButton mFloatingActionButton;
RecyclerView mRecyclerView;
ContactsAdapter mAdapter;
String contactName;
String mobileNumber;
String mobileNumberSelected;
Contacts contactsObject;
TextView noItem;
private ArrayList<Contacts> contactsArrayList;
ArrayList<String> tempList;
private Parcelable mListState;
private LinearLayoutManager mLayoutManager;
SharedPreferences mSharedPreferences;
SharedPreferences.Editor mEditor;
private boolean mCalledFromOncreate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
mCalledFromOncreate = true;
noItem = (TextView) findViewById(R.id.no_listitem_in_contacts);
noItem.setVisibility(View.GONE);
mFloatingActionButton = (FloatingActionButton) findViewById(R.id.add_fab_in_main);
contactsArrayList = new ArrayList<Contacts>();
mSharedPreferences = getPreferences(Context.MODE_PRIVATE);
mEditor = mSharedPreferences.edit();
launchConacts();
for (int i = 0; i < contactsArrayList.size(); i++) {
Log.e("name:", "" + contactsArrayList.get(i).getName());
for (int j = 0; j < contactsArrayList.get(i).getMobileNumber().size(); j++) {
Log.e("num:", contactsArrayList.get(i).getMobileNumber().get(j));
}
}
mFloatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String data = "";
int counter = 0;
for (int i = 0; i < contactsArrayList.size(); i++) {
Contacts singleContact = contactsArrayList.get(i);
if (contactsArrayList.get(i).getFlag()) {
data = data + "\n" + singleContact.getName().toString() + " " + singleContact.getSelectedMobileNumber();
counter++;
mEditor.putBoolean("checkbox_" + contactsArrayList.get(i).getName(), true);
mEditor.putString("selected_mobile_number_for_" + contactsArrayList.get(i).getName(), "" + singleContact.getSelectedMobileNumber());
} else {
mEditor.putBoolean("checkbox_" + contactsArrayList.get(i).getName(), false);
mEditor.putString("selected_mobile_number_for_" + contactsArrayList.get(i).getName(), "" + singleContact.getSelectedMobileNumber());
}
}
mEditor.commit();
Toast.makeText(ContactsActivity.this, "Selected contacts: \n" + data, Toast.LENGTH_LONG).show();
Intent intent = new Intent(ContactsActivity.this, ReportActivity.class);
intent.putExtra("TOTAL_KEY", contactsArrayList.size() + "");
intent.putExtra("SELECTED_KEY", counter + "");
startActivity(intent);
}
});
}
#Override
public void onListItemClick(final int clickedItemIndex, int whichClick) {
switch (whichClick) {
case CHECK_CLICK: {
//Toast.makeText(ContactsActivity.this, "Clicked on Checkbox: "+clickedItemIndex , Toast.LENGTH_SHORT).show();
int selectedMobileNumberPosition = 0;
String selectedMobileNumber = contactsArrayList.get(clickedItemIndex).getSelectedMobileNumber();
if (contactsArrayList.get(clickedItemIndex).getMobileNumber().size() > 1) {
final String items[] = new String[contactsArrayList.get(clickedItemIndex).getMobileNumber().size()];
for (int j = 0; j < contactsArrayList.get(clickedItemIndex).getMobileNumber().size(); j++) {
items[j] = contactsArrayList.get(clickedItemIndex).getMobileNumber().get(j);
if (items[j].contains(selectedMobileNumber)) {
selectedMobileNumberPosition = j;
}
}
AlertDialog levelDialog;
// Creating and Building the Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Please select the mobile number");
builder.setSingleChoiceItems(items, selectedMobileNumberPosition, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
mobileNumberSelected = items[item];
contactsArrayList.get(clickedItemIndex).setSelectedMobileNumber(mobileNumberSelected);
// levelDialog.dismiss();
}
});
builder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// Toast.makeText(ContactsActivity.this, "You clicked yes button", Toast.LENGTH_LONG).show();
}
});
levelDialog = builder.create();
levelDialog.show();
}
break;
}
}
}
protected void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
// Save list state
mListState = mLayoutManager.onSaveInstanceState();
state.putParcelable(LIST_STATE_KEY, mListState);
}
protected void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
// Retrieve list state and list/item positions
if (state != null)
mListState = state.getParcelable(LIST_STATE_KEY);
}
#Override
protected void onResume() {
super.onResume();
if (!mCalledFromOncreate) {
contactsArrayList.clear();
launchConacts();
mAdapter.notifyDataSetChanged();
Log.e("Inside", "onResume after clear");
}
if (mListState != null) {
mLayoutManager.onRestoreInstanceState(mListState);
}
}
void launchConacts() {
//Cursor pho = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE NOCASE ASC");
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE NOCASE ASC");
Log.i("Size is "," "+phones.getCount());
if (phones != null && (phones.getCount() > 0)) {
phones.moveToFirst();
phones.move(0);
for (int i = 0; i < phones.getCount(); i++) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumberStr = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
try {
final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
PhoneNumber phoneNumber = phoneNumberUtil.parse(phoneNumberStr, Locale.getDefault().getCountry());
PhoneNumberUtil.PhoneNumberType phoneNumberType = phoneNumberUtil.getNumberType(phoneNumber);
if (phoneNumberType == PhoneNumberType.MOBILE) {
if (name.equals(contactName)) {
phoneNumberStr = phoneNumberStr.replaceAll(" ", "");
if (phoneNumberStr.contains(mobileNumber)) {
} else {
mobileNumber = String.valueOf(phoneNumber.getNationalNumber());
if (!tempList.contains(mobileNumber)) {
// Log.e("phone: ", " " + phoneNumber);
contactsObject.setMobileNumber(mobileNumber);
tempList.add(mobileNumber);
}
}
} else {
if (contactsObject != null) {
contactsArrayList.add(contactsObject);
Log.e("object added", contactsObject.getName());
}
contactsObject = new Contacts();
tempList = new ArrayList<String>();
contactName = name;
mobileNumber = String.valueOf(phoneNumber.getNationalNumber());
tempList.add(mobileNumber);
// Log.e("name: ", " " + name);
// Log.e("phone: ", " " + mobileNumber);
contactsObject.setName(name);
contactsObject.setMobileNumber(mobileNumber);
contactsObject.setFlag(mSharedPreferences.getBoolean("checkbox_" + name, false));
contactsObject.setSelectedMobileNumber(mSharedPreferences.getString("selected_mobile_number_for_" + name, mobileNumber));
}
}
} catch (Exception e) {
} finally {
}
if (phones.isLast()) {
contactsArrayList.add(contactsObject);
// Log.e("object added last>>>>>", contactsObject.getName());
}
phones.moveToNext();
}
//phones.close();
}
mRecyclerView = (RecyclerView)
findViewById(R.id.recycler_view_in_contacts);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new
LinearLayoutManager(getApplicationContext());
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new
ContactsAdapter(contactsArrayList, ContactsActivity.this);
mRecyclerView.setAdapter(mAdapter);
if (contactsArrayList.size() == 0)
{
noItem.setVisibility(View.VISIBLE);
}
}
#Override
protected void onPause() {
super.onPause();
mCalledFromOncreate = false;
}
}
Here is what I found which is adding one more item in your list
Try removing:
if (contactsObject != null) {
contactsArrayList.add(contactsObject);
Log.e("object added : ", contactsObject.getName);
}
Hope this helps.

ProgressDialog.show() is not showing the progress dialog

I am trying to display a progress dialog inside a fragment.But progressbar.show() do not have any effect.However,I noticed a strange behaviour,if i call showPopUp() method twice,it does show the progress dialog,but unable to dismiss().
package com.snapbizz.snapdashboard.Tabs.v1;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.snapbizz.snapdashboard.Core.v1.SalesData;
import com.snapbizz.snapdashboard.R;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class DashBoardSalesTab extends Fragment {
LinearLayout salesListContainer, salesBarConatainer;
LayoutInflater layoutInflater;
SalesData salesData;
ProgressDialog progressDialog;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.sales_page_layout, container, false);
return rootView;
}
public void showPopUp() {
progressDialog = new ProgressDialog(getContext(), ProgressDialog.THEME_HOLO_LIGHT);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("loading the page...");
progressDialog.setProgressNumberFormat(null);
progressDialog.setProgressPercentFormat(null);
progressDialog.setIndeterminate(true);
progressDialog.show();
}
public void synchronizeScrollers() {
getActivity().findViewById(R.id.page_scroller).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
getActivity().findViewById(R.id.table_scroller).getParent()
.requestDisallowInterceptTouchEvent(true);
return false;
}
});
getActivity().findViewById(R.id.table_scroller).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
v.getParent().requestDisallowInterceptTouchEvent(true);
return false;
}
});
}
public void renderSalesGraph(List<String[]> values, Float totalSumY) throws Exception {
salesBarConatainer.removeAllViews();
for (String[] value : values) {
View barView = layoutInflater.inflate(R.layout.bar_char_item_layout, salesBarConatainer, false);
float sumOfSalesForTheDay = Float.parseFloat((value[0] == null) ? "0" : value[0]);
float weightofBar = sumOfSalesForTheDay / totalSumY;
barView.findViewById(R.id.bar_y).setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, weightofBar));
((TextView) barView.findViewById(R.id.value_y)).setText(
(sumOfSalesForTheDay == 0.0f ? "" :
getActivity().getResources().getString(R.string.rupee_symbol) + sumOfSalesForTheDay + "")
);
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy/MM/dd");
SimpleDateFormat outputFormat = new SimpleDateFormat("dd-MMM-yyyy");
Date renderingDate = inputFormat.parse(value[2]);
String[] date = outputFormat.format(renderingDate).split("-");
((TextView) barView.findViewById(R.id.value_x_date)).setText(date[0] + " " + date[1]);
((TextView) barView.findViewById(R.id.value_x_year)).setText(date[2]);
salesBarConatainer.addView(barView);
}
}
public void renderSalesGraphForMonths(List<String[]> values, Float totalSumY) throws Exception {
LinearLayout salesBarConatainer = (LinearLayout) getActivity().findViewById(R.id.bars_container);
salesBarConatainer.removeAllViews();
for (String[] value : values) {
View barView = layoutInflater.inflate(R.layout.bar_char_item_layout, salesBarConatainer, false);
float sumOfSalesForTheDay = Float.parseFloat((value[0] == null) ? "0" : value[0]);
float weightofBar = sumOfSalesForTheDay / totalSumY;
barView.findViewById(R.id.bar_y).setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, weightofBar));
((TextView) barView.findViewById(R.id.value_y)).setText(
(sumOfSalesForTheDay == 0.0f ? "" :
getActivity().getResources().getString(R.string.rupee_symbol) + sumOfSalesForTheDay + "")
);
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy/MM");
SimpleDateFormat outputFormat = new SimpleDateFormat("MMM-yyyy");
Date renderingDate = inputFormat.parse(value[2]);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, renderingDate.getMonth());
cal.set(Calendar.DAY_OF_MONTH, 1);
barView.setOnClickListener(new MonthBarClickListener(cal));
String[] date = outputFormat.format(renderingDate).split("-");
((TextView) barView.findViewById(R.id.value_x_date)).setText(date[0]);
((TextView) barView.findViewById(R.id.value_x_year)).setText(date[1]);
salesBarConatainer.addView(barView);
}
}
public String[] addTOSalesTable(String date, boolean header) throws Exception {
List<String[]> values = salesData.getSalesTableData(date);
String[] value = values.get(0);
String[] newValue = {value[0], value[1], date};
String totalSales = (value[0] == null) ? "0" : value[0];
String totalCredit = (value[1] == null) ? "0" : value[1];
String totalCash = (Float.parseFloat(totalSales) - Float.parseFloat(totalCredit)) + "";
String rupeeSymbol = getActivity().getResources().getString(R.string.rupee_symbol);
if (!header) {
View salesRow = layoutInflater.inflate(R.layout.sales_page_table_row_layout, salesListContainer, false);
((TextView) (salesRow.findViewById(R.id.sale_date))).
setText(date);
((TextView) (salesRow.findViewById(R.id.sales_total_sale))).
setText(rupeeSymbol + " " + totalSales);
((TextView) (salesRow.findViewById(R.id.sales_total_cash))).
setText(rupeeSymbol + " " + totalCash);
((TextView) (salesRow.findViewById(R.id.sales_total_credit))).
setText(rupeeSymbol + " " + totalCredit);
((TextView) (salesRow.findViewById(R.id.sales_ttoal_coupon))).
setText(rupeeSymbol + " " + "0");
if (salesListContainer.getChildCount() % 2 != 0) {
salesRow.setBackgroundColor(getResources().getColor(R.color.table_row_alternate_color));
}
salesListContainer.addView(salesRow);
} else {
((TextView) (getActivity().findViewById(R.id.sales_header_total_sales))).
setText(rupeeSymbol + " " + totalSales);
((TextView) (getActivity().findViewById(R.id.sales_header_total_cash))).
setText(rupeeSymbol + " " + totalCash);
((TextView) (getActivity().findViewById(R.id.sales_header_total_credit))).
setText(rupeeSymbol + " " + totalCredit);
((TextView) (getActivity().findViewById(R.id.sales_header_total_coupon))).
setText(rupeeSymbol + " " + "0");
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Date presentDate = new Date();
((TextView) (getActivity().findViewById(R.id.sales_header_day))).
setText(date.contentEquals(dateFormat.format(presentDate)) ? "Today" : date);
}
return newValue;
}
public void getMonths() throws Exception {
Calendar cal = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM");
List<String[]> values = new ArrayList<>();
float totalSumY = 0.0f;
for (int i = 0; i < 12; i++) {
cal.add(Calendar.MONTH, (i == 0) ? 0 : -1);
String date = dateFormat.format(cal.getTime());
String[] value = salesData.getSalesDataForMonth(date);
String[] newValue = {value[0] == null ? "0" : value[0], value[1] == null ? "0" : value[1], date};
totalSumY += Float.parseFloat(value[0] == null ? "0" : value[0]);
values.add(newValue);
}
renderSalesGraphForMonths(values, totalSumY);
}
public void initChart() {
FrameLayout dayButton = (FrameLayout) getActivity().findViewById(R.id.day_button);
FrameLayout monthButton = (FrameLayout) getActivity().findViewById(R.id.month_button);
dayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
((TextView) getActivity().findViewById(R.id.button_day_text)).setTextColor(
getResources().getColor(R.color.dark_darkblue)
);
((TextView) getActivity().findViewById(R.id.button_day_text)).
setBackground(getResources().getDrawable(R.drawable.button_border_active));
((TextView) getActivity().findViewById(R.id.button_month_text)).setTextColor(
getResources().getColor(R.color.default_text_color)
);
((TextView) getActivity().findViewById(R.id.button_month_text)).
setBackground(getResources().getDrawable(R.drawable.button_border));
generateTablesRows(Calendar.getInstance(), 60, -1);
} catch (Exception e) {
e.printStackTrace();
}
}
});
monthButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
((TextView) getActivity().findViewById(R.id.button_month_text)).setTextColor(
getResources().getColor(R.color.dark_darkblue)
);
((TextView) getActivity().findViewById(R.id.button_month_text)).
setBackground(getResources().getDrawable(R.drawable.button_border_active));
((TextView) getActivity().findViewById(R.id.button_day_text)).setTextColor(
getResources().getColor(R.color.default_text_color)
);
((TextView) getActivity().findViewById(R.id.button_day_text)).
setBackground(getResources().getDrawable(R.drawable.button_border));
getMonths();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void generateTablesRows(Calendar cal, int limit, int increment) throws Exception {
salesListContainer.removeAllViews();
float totalSumY = 0.0f;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
List<String[]> barGraphValues = new ArrayList<>();
for (int i = 0; i < limit; i++) {
cal.add(Calendar.DATE, (i == 0) ? 0 : increment);
String date = dateFormat.format(cal.getTime());
String[] value = addTOSalesTable(date, (i == 0) ? true : false);
totalSumY += Float.parseFloat((value[0] == null) ? "1" : value[0]);
barGraphValues.add(value);
}
renderSalesGraph(barGraphValues, totalSumY);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
showPopUp();
layoutInflater = LayoutInflater.from(getContext());
salesListContainer = (LinearLayout) (getActivity().findViewById(R.id.sales_list_container));
salesListContainer.removeAllViews();
salesBarConatainer = (LinearLayout) getActivity().findViewById(R.id.bars_container);
salesBarConatainer.removeAllViews();
new SalesTabLoader().execute();
}
public class MonthBarClickListener implements View.OnClickListener {
Calendar cal;
public MonthBarClickListener(Calendar cal) {
this.cal = cal;
}
#Override
public void onClick(View v) {
try {
//new SalesAsyncTask(cal).execute(cal.getActualMaximum(Calendar.DAY_OF_MONTH),1);
generateTablesRows(cal, cal.getActualMaximum(Calendar.DAY_OF_MONTH), 1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class SalesTabLoader extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
salesData = new SalesData(getContext());
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
try {
initChart();
generateTablesRows(Calendar.getInstance(), 60, -1);
} catch (Exception e) {
e.printStackTrace();
} finally {
synchronizeScrollers();
progressDialog.dismiss();
}
}
}
}
Try like this :
progressDialog = new ProgressDialog(getActivity());
And if you wish to customize your dialog and put self created Layout in it.
/**
* Created by vivek on 18/10/16.
*/
public class CustomDialog {
private static Dialog dialog;
private static Context context;
public CustomDialog(Context context) {
this.context = context;
}
/**
* Comman progress dialog ... initiates with this
*
* #param message
* #param title
*/
public static void showProgressDialog(Context context, String title, String message) {
if (dialog == null)
{
dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_loader);
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
}
public static boolean isProgressDialogRunning() {
if (dialog != null && dialog.isShowing()) {
return true;
} else return false;
}
/**
* Dismiss comman progress dialog
*/
public static void dismissProgressDialog() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
dialog = null;
}
}
} // End of main class over here ...
Replace this:-
progressDialog = new ProgressDialog(getContext(), ProgressDialog.THEME_HOLO_LIGHT);
with
progressDialog = new ProgressDialog(getActivity());
May be. you are showing two progressdialog and both of that progressbar on screen.. but when you dismiss your progressbar at that time the previous one is override by other one before you dismiss first one .. so the firstone is always in screen. that's the issue.
I tried everything.But none of the answers solved the issue.However,i solved it by overriding onResume() method in the fragment.
Thanks All.

How to display Dialog in Contacts

I used this code for a button, after that I am in the Contacts Activity:
btnPhonebook.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent pb = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(pb, 1);
}
});
After that, there is a contact list with many contacts. Now I want that, whenever I clicked to a contact, a dialog is displayed. How can I do that. Could anyone help me because currently I have no issue how to make it. I have tried with this code but it did not work.
Dialog dialog = new Dialog(this);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose a phone number");
ListView lp = new ListView(this);
lp.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, _listPhoneNumber));
builder.setView(lp);
dialog = builder.create();
Also I put the above code in onActivityResult() method.
Thanks in advance.
Instead of using the Built in Intent to display contacts.. why don't you build the List yourself and then do what you plan to do.
OR
Did you set your dialog to .show()?
It is very simple,
progDailog = ProgressDialog.show(loginAct,"Process ", "please wait....",true,true);
new Thread ( new Runnable()
{
public void run()
{
// your loading code goes here
}
}).start();
Handler progressHandler = new Handler()
{
public void handleMessage(Message msg1)
{
progDailog.dismiss();
}
}
You cannot show Dialog in native Contacts app.
However you can fetch Contacts by yourself and show them in a ListView with CheckBox and proceed to next step.
Here is a simplest ListView to show contacts. you can edit it by yourself.
I Have did this in my application how we can get contact detail from listview ,
using this Data you can Display your dialog.
lv.setClickable(true);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView <? > arg0, View arg1, int position, long arg3) {
Object o = lv.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), o.toString(), Toast.LENGTH_LONG).show();
String infoString = o.toString();
String arr[] = infoString.split(",");
String names[] = arr[1].split("=");
id = Integer.parseInt(names[1]);
System.out.println("info" + id);
db = dh.getReadableDatabase();
String select = "select * from '" + dh.tablename + "' WHERE adb_id='" + id + "' ";
Cursor c = db.rawQuery(select, null);
if (c.moveToFirst()) {
name.setText(c.getString(1));
address.setText(c.getString(2));
contact.setText(c.getString(3));
}
}
});
If you want to use dialog in contact then you have to make your own custom layout for contact.. See below code for example...
on button click
public static final int NUMBER_SELECT = 1;
Intent intent = new Intent(clsBlockNumbers.this,CallLog_Activity.class);
startActivityForResult(intent,NUMBER_SELECT);
in the same Activity write/make onActivityResult
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
switch(requestCode) {
case NUMBER_SELECT:
if (resultCode == RESULT_OK) {
String number = data.getStringExtra("SelectedNumber");
if(number == null)
{
Toast.makeText(this, "No Record found: ", Toast.LENGTH_LONG).show();
}
else
{
//Your code
}
break;
}
}
}
CallLog_Activity.java
package com.demo;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
public class CallLog_Activity extends Activity implements OnItemClickListener
{
ArrayList<String> strAyyNumber,strAyyType,listNumber, strType, strAyyName ;
private CallLogListAdapter adapter ;
CallLog callLog;
String noType;
ListView listCallLog;
private String[] listCallLog_arr={};
Cursor cursor;
String strArr;
TextView tv, tv1, txtEmptyMsg;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.calllog_list);
callLog = new CallLog();
listCallLog = (ListView)findViewById(R.id.list);
strAyyNumber = new ArrayList<String>();
strAyyType = new ArrayList<String>();
strAyyName = new ArrayList<String>();
listNumber = new ArrayList<String>();
strType = new ArrayList<String>();
System.out.println("In Call log list activity");
try
{
final String[] projection = null;
final String selection = null;
final String[] selectionArgs = null;
final String sortOrder = "DATE DESC";
Cursor cursor = this.getContentResolver().query(
Uri.parse("content://call_log/calls"),
projection,
selection,
selectionArgs,
sortOrder);
if (cursor != null)
{
//Loop through the call log.
while (cursor.moveToNext())
{
//Common Call Log Items
String callNumber = cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls.NUMBER));
strAyyNumber.add(callNumber);
String callType = cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls.TYPE));
strAyyType.add(callType);
String callName = cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls.CACHED_NAME));
strAyyName.add(callName);
}
for(int i=0;i<strAyyNumber.size();i++)
{
String no = strAyyNumber.get(i).toString();//.concat("\n").concat(strAyyType.get(i).toString());
Log.d("No length ", "No length ::" + no.length());
listNumber.add(no);
}
listCallLog_arr = listNumber.toArray(new String[listNumber.size()]);
Log.d("size", "list listCallLog_arr"+ listCallLog_arr.length);
if(!listNumber.isEmpty())
{
listCallLog.setVisibility(View.VISIBLE);
adapter = new CallLogListAdapter(CallLog_Activity.this,R.layout.calllog_list_row, listCallLog_arr,strAyyNumber,strAyyType,strAyyName);
listCallLog.setAdapter(adapter);
}
else
{
txtEmptyMsg = (TextView)findViewById(R.id.txtEmptyMsg);
txtEmptyMsg.setVisibility(View.VISIBLE);
txtEmptyMsg.setText("No Record found Press Back to Continue");
}
listCallLog.setOnItemClickListener(this);
}
listCallLog.setOnItemClickListener(this);
}
catch(Exception e)
{
e.printStackTrace();
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id)
{
String o = arg0.getItemAtPosition(position).toString();
Intent returnIntent = new Intent();
StringBuffer sb = new StringBuffer(o);
sb.reverse().setLength(10);
Log.d("Item click", "String buffer"+ sb);
String revercenum = sb.toString().trim();
Log.d("Item click", "revercenum "+ revercenum);
StringBuffer sb1 = new StringBuffer(revercenum);
sb1.reverse();
Log.d("Item click", "sb1 "+ sb1);
String revercenum1 = sb1.toString().trim();
revercenum1.replace("+", "");
Log.d("Item click", "revercenum 1"+ revercenum1);
returnIntent.putExtra("SelectedNumber",revercenum1.replace("+", ""));
setResult(RESULT_OK,returnIntent);
finish();
}
}
colllog_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="#+id/list"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:visibility="gone"
/>
<TextView android:id="#+id/txtEmptyMsg"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:textStyle="bold"
android:textSize="25dp"
android:text=""
android:visibility="gone"
/>
</LinearLayout>
colllog_list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/txtCallLogName"
android:layout_width="wrap_content" android:layout_height="fill_parent"
android:textSize="20dp" android:layout_margin="10dp"
android:layout_weight="1" />
<TextView
android:id="#+id/txtCallLogNumber"
android:layout_width="wrap_content" android:layout_height="fill_parent"
android:textSize="20dp" android:layout_weight="1"
android:layout_marginLeft="10dp" android:layout_marginBottom="10dp"
android:layout_marginTop="5dp" android:layout_marginRight="10dp" />
</LinearLayout>
<TextView
android:id="#+id/txtCallLogType"
android:layout_width="wrap_content" android:layout_height="fill_parent"
android:textSize="12dp" android:layout_marginBottom="10dp"
android:layout_marginTop="10dp" android:layout_marginRight="10dp"
android:layout_alignParentRight="true" />
</RelativeLayout>
CallLogListAdapter.java
package com.Demo;
import java.util.ArrayList;
import android.app.Activity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class CallLogListAdapter extends ArrayAdapter<Object>
{
private static final String TAG = "CallLogListAdapter";
private LayoutInflater inflater = null;
private int resource;
private Activity activity;
CallLog callLog ;
String[] strTemp;
ArrayList<String> arrayItem = new ArrayList<String>();
ArrayList<String> ayyType = new ArrayList<String>();
ArrayList<String> tempType = new ArrayList<String>();
ArrayList<String> ayyName = new ArrayList<String>();
ArrayList<String> tempName = new ArrayList<String>();
ArrayList<String> tempName1 = new ArrayList<String>();
ArrayList<String> tempNo = new ArrayList<String>();
String strType, strName, strName1, strNo ;
String[] tmpName, tmpName1, tmpNo;
public CallLogListAdapter(Activity activity, int resorce, String[] strTemp, ArrayList<String> arryListNumber, ArrayList<String> arryListType, ArrayList<String> arryListName)
{
super(activity, resorce,strTemp);
this.resource = resorce;
this.activity = activity;
this.strTemp = strTemp;
Log.d("in adapter", "In Adapter");
arrayItem = arryListNumber;
ayyType = arryListType;
ayyName = arryListName;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
Log.d("in adapter", "In get View");
ViewHolder holder;
if (convertView == null)
{
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
convertView = layoutInflater.inflate(resource, parent, false);
holder = new ViewHolder();
holder.txtName = (TextView)convertView.findViewById(R.id.txtCallLogName);
holder.txtNumber = (TextView)convertView.findViewById(R.id.txtCallLogNumber);
holder.txtType = (TextView)convertView.findViewById(R.id.txtCallLogType);
holder.txtName.setVisibility(View.VISIBLE);
try
{
for(int i=0;i<ayyName.size();i++)
{
strName = ayyName.get(i);
Log.d("in get view in ", "Name is: **"+ strName);
tempName.add(strName);
}
tmpName = tempName.toArray(new String[tempName.size()]);
if(tmpName[position] == null)
{
holder.txtName.setVisibility(View.GONE);
}
else
{
holder.txtName.setVisibility(View.VISIBLE);
holder.txtNumber.setTextSize(12);
holder.txtName.setText(""+ tmpName[position]);
}
}
catch (NullPointerException e)
{
e.printStackTrace();
}
for(int i=0;i<arrayItem.size();i++)
{
strNo = arrayItem.get(i);//.toString();
Log.d("in get view in ", "Number is: **"+ strNo);
tempNo.add(strNo);
}
String[] tmpNo = tempNo.toArray(new String[tempNo.size()]);
Log.d("in get view ", "Number is String[]** : "+ tmpNo[position]);
holder.txtNumber.setText(""+ tmpNo[position]);
for(int i=0;i<ayyType.size();i++)
{
strType = ayyType.get(i).toString();
if(strType.equalsIgnoreCase("1"))
{
strType = "Incoming Call";
}
else if(strType.equalsIgnoreCase("2"))
{
strType = "Outgoing Call";
}
else if(strType.equalsIgnoreCase("3"))
{
strType = "Missed Call";
}
tempType.add(strType);
}
String[] tmpType = tempType.toArray(new String[tempType.size()]);
holder.txtType.setText(""+ tmpType[position]);
convertView.setTag(holder);
} else {
holder=(ViewHolder)convertView.getTag();
}
return convertView;
}
public static class ViewHolder
{
private TextView txtNumber, txtType, txtName;
}
}
I hope it may be help you.. :)

Android MediaPlayer Prepare Failed

I've been trying to make a Javanese language translation along with the sound. the translation result is displayed successfully, but the sound won't come out. it throws exception.
Java.io.IOException: Prepare failed: status=0x1
at android.media.MediaPlayer.prepare(Native Method)
at com.cinta.jawa.JawaSearchActivity.playAudio(JawaSearchActivity.java:51)
at com.cinta.jawa.JawaSearchActivity$1.onClick(JawaSearchActivity.java:178)
at android.view.View.performClick(View.java:2408)
at android.view.View$PerformClick.run(View.java:8816)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
it says that i got wrong at line 52 and 179, but i have no idea what makes it wrong. Can anybody help me?
here is the code:
package com.cinta.jawa;
import java.io.IOException;
import java.util.ArrayList;
import org.xmlpull.v1.XmlPullParserException;
import android.app.Activity;
import android.content.res.XmlResourceParser;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class JawaSearchActivity extends Activity {
private EditText etSearch;
private TextView tvResult;
Jawa jawa = new Jawa(this);
boolean booSearch = false;
public static MediaPlayer myplayer = new MediaPlayer();
public static ArrayList<Uri> pathlist = new ArrayList<Uri>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
etSearch = (EditText) findViewById(R.id.editTextSearch);
tvResult = (TextView) findViewById(R.id.textViewResult);
Button btnSearch = (Button) findViewById(R.id.button_search);
btnSearch.setOnClickListener(onClickListener);
}
public void playAudio() {
try {
if (myplayer.isPlaying()) {
myplayer.stop();
myplayer.release();
}
if (pathlist.size() >= 1) {
for (int i = 0; i< pathlist.size();i++){
Uri path = pathlist.get(i);
myplayer.setDataSource(this, path);
myplayer.prepare(); /*this is the error line*/
myplayer.start();
}
}
} catch (Exception e) {
e.printStackTrace();
}
myplayer.setLooping(true);
}
private String[] getWord(XmlResourceParser words, String strWord)
throws XmlPullParserException, IOException {
int eventType = -1;
String[] strReturn = new String[2];
while (eventType != XmlResourceParser.END_DOCUMENT) {
if (eventType == XmlResourceParser.START_TAG) {
String strName = words.getName();
if (strName.equals("word")) {
String wordValue = words.getAttributeValue(null, "key");
if (wordValue.equalsIgnoreCase(strWord)) {
strReturn[0] = words.getAttributeValue(null, "file");
strReturn[1] = words.getAttributeValue(null,
"translate");
return strReturn;
}
}
}
eventType = words.next();
}
return strReturn;
}
OnClickListener onClickListener = new OnClickListener() {
public void onClick(View v) {
XmlResourceParser jawaDictionary = getResources()
.getXml(R.xml.jawa);
String strWord[] = new String[2];
String[] strNumb = null;
int intstrNumb = 0;
String angkaBo = null;
System.out.println("AWAL NIHH??" + angkaBo);
Long angka = null;
boolean booFind = false;
StringBuilder strbTranslate = new StringBuilder();
myplayer.reset();
myplayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer arg0) {
for (int i = 0; i< pathlist.size();i++){
pathlist.remove(i);
if (pathlist.size() >= 1) {
myplayer.reset();
playAudio();
}
}
}
});
String strWords = etSearch.getText().toString().trim();
String[] astrWord = strWords.split(" ");
int intCountWords = astrWord.length;
for (int i = 0; i < intCountWords; i++) {
try {
String perWord = astrWord[i].trim();
int perWordL = perWord.length();
for (int x = 0; x < perWordL; x++) {
if (Character.isDigit(perWord.charAt(x))) {
angka = Long.parseLong(perWord);
}
}
strWord = getWord(jawaDictionary, astrWord[i].trim());
System.out.println("STRWORD NYE APAAN??" + strWord[0]);
jawaDictionary.close();
jawaDictionary = getResources().getXml(R.xml.jawa);
if (strWord[0] != null) {
System.out.println("MASUK SINI GA SIHHHHHH??");
strbTranslate.append(strWord[1]);
strbTranslate.append(" ");
System.out.println("COBA DILIAT " + strbTranslate);
System.out.println("KALOYANG INI?? " + pathlist);
tvResult.setText(strbTranslate);
booSearch = true;
} else {
System.out.println("MASUK MANA DONK??");
if (angka != null) {
angkaBo = NumberScanActivity.convert(angka);
System.out.println("COBA LIAT INI MUNCUL GAKK??"
+ angkaBo);
String angkaNih = angkaBo.trim();
strNumb = angkaNih.split(" ");
System.out.println("HOHOHEHEHEHK??" + angkaNih);
System.out.println("BLUKUTUKKK??" + strNumb);
intstrNumb = strNumb.length;
for (int y = 0; y < intstrNumb; y++) {
System.out
.println("MASUK SINI KAGA?? HAYOOOOOO "
+ strNumb[y]);
strbTranslate.append(strNumb[y]);
strbTranslate.append(" ");
}
tvResult.setText(strbTranslate);
booSearch = true;
}
}
} catch (Exception e) {
}
}
String fullText = strbTranslate.toString();
pathlist = SyllableScanActivity.convertSentenceToSyl(fullText);
System.out.println("COBA LIAT ISI PATHLIS APAAN>>>>>> "+pathlist);
if (!myplayer.isPlaying()) {
playAudio(); /*this is the error line*/
}
if (booFind == false) {
if (booSearch == false)
tvResult.setText("Sorry, No Result");
}
}
};
}
See this link this will help you to solve your problem.
I am using this code in my project for playing audio files. I am not using mediaPlayer.prepair();
see if this help's you...
bGSound = MediaPlayer.create(MusicPlay.this,R.drawable.music_ground);
float bGLeftVol = (float) (bGSoundVolume.getProgress()/100.0);
float bGRightVol = (float) (bGSoundVolume.getProgress()/100.0);
bGSound.setLooping(true);
bGSound.setVolume(bGLeftVol, bGRightVol);
bGSound.start();

Categories

Resources