rotating text,marquee is not appropriate - android

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" />

Related

Unexpectedly changing widget in xamarin android

I have a xamarin forms app and a widget for Android platform in it.
The widget displays a calendar with highlited days according to the app's logic. It consists of a ListView filled with 7 TextViews text and color of which is made in-app. But I've encountered 2 annoying troubles:
trouble with sizing
During the development and launching the app on the emulator I made it look just like I wanted to. But when I deployed it on my personal device I've met with another result. I guess the trouble is in different desktop cell size on different devices. The code of all .xml files is given below.
widgetinfo.xml:
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="145dp"
android:minHeight="110dp"
android:initialLayout="#layout/widget_layout"
android:resizeMode="horizontal"
android:updatePeriodMillis="1800000"/>
list_row.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/d1"
android:layout_width="31dp"
android:layout_height="29dp"
android:textAlignment="center"
android:background="#android:color/background_light"/>
<TextView
android:id="#+id/d2"
android:layout_width="31dp"
android:layout_height="29dp"
android:textAlignment="center"
android:background="#android:color/background_light"/>
<TextView
android:id="#+id/d3"
android:layout_width="31dp"
android:layout_height="29dp"
android:textAlignment="center"
android:background="#android:color/background_light"/>
<TextView
android:id="#+id/d4"
android:layout_width="31dp"
android:layout_height="29dp"
android:textAlignment="center"
android:background="#android:color/background_light"/>
<TextView
android:id="#+id/d5"
android:layout_width="31dp"
android:layout_height="29dp"
android:textAlignment="center"
android:background="#android:color/background_light"/>
<TextView
android:id="#+id/d6"
android:layout_width="31dp"
android:layout_height="29dp"
android:textAlignment="center"
android:background="#android:color/background_light"/>
<TextView
android:id="#+id/d7"
android:layout_width="31dp"
android:layout_height="29dp"
android:textAlignment="center"
android:background="#android:color/background_light"/>
</LinearLayout>
widget_layout.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#android:color/white">
<ListView
android:id="#+id/listViewWidget"
android:choiceMode="none"
android:clickable="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
So, the question - is there any way to make all the textviews look the same at all devices? I don't really need to change their size when resizing the widget, but such an option could also be really useful.
trouble with re-colouring.
when I press onto my widget (it always happens in random number of presses - sometimes it happens after the first one, sometimes - after about 20), or try to resize it, the colours go mad and change without any logic.
I was trying to add breakpoints into the ListProvider - they just don't react. I thought the trouble is with some intent coming while interacting the widget, but OnRecieve method doesn't react too. I just can't understand what makes the widget to change the colours. Codes are also below.
ListProvider.cs:
public class ListProvider : Java.Lang.Object, RemoteViewsService.IRemoteViewsFactory
{
private List<ListItem> listItemList = new List<ListItem>();
private List<CallbackMyWorks> works = new List<CallbackMyWorks>();
private Context context;
private int d;
private int i;
private int k;
private DateTime dt;
public ListProvider(Context contextNew)
{
context = contextNew;
k = DateTime.DaysInMonth(DateTime.Today.Year, DateTime.Today.Month);
i = 0;
dt = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1);
d = (int)dt.DayOfWeek;
if (d == 0)
d = 7;
works = LoadFromFile();
populateListItem();
}
public RemoteViews GetViewAt(int position)
{
RemoteViews remoteView = new RemoteViews(context.PackageName, Resource.Layout.list_row);
for (int j=0; j<7; j++)
{
FillList(remoteView, position, j);
}
return remoteView;
}
private void FillList(RemoteViews remoteView, int i, int j)
{
int res = 0;
if (j == 0)
res = Resource.Id.d1;
else if (j == 1)
res = Resource.Id.d2;
else if (j == 2)
res = Resource.Id.d3;
else if (j == 3)
res = Resource.Id.d4;
else if (j == 4)
res = Resource.Id.d5;
else if (j == 5)
res = Resource.Id.d6;
else if (j == 6)
res = Resource.Id.d7;
remoteView.SetTextViewText(res, listItemList[i].days[j]);
if ((i == 0 && int.Parse(listItemList[i].days[j]) > 7) || (i > 3 && int.Parse(listItemList[i].days[j]) < 15))
remoteView.SetInt(res, "setBackgroundColor", Android.Graphics.Color.Gray);
else
{
if (listItemList[i].specs[j].Equals("1"))
{
remoteView.SetInt(res, "setBackgroundColor", Android.Graphics.Color.ParseColor(Preferences.Get("dayColor", "#bf3737")));
remoteView.SetTextColor(res, Android.Graphics.Color.White);
}
else if (listItemList[i].specs[j].Equals("2"))
{
remoteView.SetInt(res, "setBackgroundColor", Android.Graphics.Color.ParseColor(Preferences.Get("nightColor", "#203080")));
remoteView.SetTextColor(res, Android.Graphics.Color.White);
}
else if (listItemList[i].specs[j].Equals("8") | listItemList[i].specs[j].Equals("7") | listItemList[i].specs[j].Equals("4"))
{
remoteView.SetInt(res, "setBackgroundColor", Android.Graphics.Color.ParseColor(Preferences.Get("specColor", "#2f8254")));
remoteView.SetTextColor(res, Android.Graphics.Color.White);
}
else if (listItemList[i].specs[j].Equals("О"))
{
remoteView.SetInt(res, "setBackgroundColor", Android.Graphics.Color.ParseColor(Preferences.Get("vacColor", "#FFE4C4")));
remoteView.SetTextColor(res, Android.Graphics.Color.White);
}
}
}
private void populateListItem()
{
ListItem listItem = new ListItem();
if (d != 1)
{
for (int j = 0; j < d - 1; j++)
{
listItem.days[j] = dt.AddDays(-1 * (d - j - 1)).Day.ToString();
}
}
for (int j = d; j <= 7; j++)
{
i++;
DateTime dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, i);
var find = works.FirstOrDefault(x => x.getDate() == dt);
if (find != null)
{
listItem.specs[j - 1] = find.getType();
}
else
listItem.specs[j - 1] = "0";
listItem.days[j - 1] = i.ToString();
}
listItemList.Add(listItem);
for (int z = 0; z <= 4; z++)
{
AddFullWeek();
}
}
private void AddFullWeek()
{
ListItem listItem = new ListItem();
for (int j = 0; j < 7; j++)
{
i++;
DateTime dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, i);
var find = works.FirstOrDefault(x => x.getDate() == dt);
if (find != null)
{
listItem.specs[j] = find.getType();
}
else
listItem.specs[j] = "0";
listItem.days[j] = i.ToString();
if (i == k)
i = 0;
}
listItemList.Add(listItem);
}
public int Count { get { return listItemList.Count; } }
public long GetItemId(int position)
{
return position;
}
private int cellNum(int col)
{
return 0;
}
public RemoteViews LoadingView { get { return null; } }
public int ViewTypeCount { get { return 1; } }
public bool HasStableIds { get { return true; } }
public void OnCreate()
{
// throw new NotImplementedException();
}
public void OnDataSetChanged()
{
// throw new NotImplementedException();
}
public void OnDestroy()
{
// throw new NotImplementedException();
}
private List<CallbackMyWorks> LoadFromFile()
{
try
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string filePath = Path.Combine(path, "calPage.ods");
string json;
using (var file = File.Open(filePath, FileMode.Open, FileAccess.Read))
using (var strm = new StreamReader(file))
{
json = strm.ReadToEnd();
}
return JsonConvert.DeserializeObject<List<CallbackMyWorks>>(json);
}
catch (Exception) { return new List<CallbackMyWorks>(); }
}
}
WidgetProvider.cs:
[BroadcastReceiver(Label = "Календарь")]
[IntentFilter(new string[] { "android.appwidget.action.APPWIDGET_UPDATE" })]
[MetaData("android.appwidget.provider", Resource = "#xml/widgetinfo")]
public class WidgetProvider : AppWidgetProvider
{
public override void OnUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
{
base.OnUpdate(context, appWidgetManager, appWidgetIds);
int N = appWidgetIds.Length;
for (int i = 0; i < N; i++)
{
RemoteViews remoteViews = updateWidgetListView(context, appWidgetIds[i]);
appWidgetManager.UpdateAppWidget(appWidgetIds[i], remoteViews);
}
}
private RemoteViews updateWidgetListView(Context context, int appWidgetId)
{
RemoteViews remoteViews = new RemoteViews(context.PackageName, Resource.Layout.widget_layout);
string PACKAGE_NAME = context.PackageName;
Intent svcIntent = new Intent(context, typeof(WidgetService));
svcIntent.SetPackage(PACKAGE_NAME);
svcIntent.PutExtra(AppWidgetManager.ExtraAppwidgetId, appWidgetId);
svcIntent.SetData(Android.Net.Uri.Parse(svcIntent.ToUri(IntentUriType.AndroidAppScheme)));
remoteViews.SetRemoteAdapter(Resource.Id.listViewWidget, svcIntent);
return remoteViews;
}
}
Could you please help me with this?

Open a actvity when a if statement comes true

Hi I want to open a activity when a if statement comes true. like "if gameStatus are equal to 12, then open scoreActivity". The Code:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.GridLayout;
import java.util.Random;
import android.os.Build;
import android.os.Handler;
public class Game6x4Activity extends AppCompatActivity implements View.OnClickListener {
private int numberOfElements;
private int[] buttonGraphicLocations;
private MemoryButton selectedButton1;
private MemoryButton selectedButton2;
private boolean isBusy = false;
public int gameStatus;
public int gameScore;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_mode);
gameScore = 0;
gameStatus = 0;
GridLayout gridLayout = (GridLayout)findViewById(R.id.grid_layout_6x4);
int numColumns = gridLayout.getColumnCount();
int numRow = gridLayout.getRowCount();
numberOfElements = numColumns * numRow;
MemoryButton[] buttons = new MemoryButton[numberOfElements];
int[] buttonGraphics = new int[numberOfElements / 2];
buttonGraphics[0] = R.drawable.card1;
buttonGraphics[1] = R.drawable.card2;
buttonGraphics[2] = R.drawable.card3;
buttonGraphics[3] = R.drawable.card4;
buttonGraphics[4] = R.drawable.card5;
buttonGraphics[5] = R.drawable.card6;
buttonGraphics[6] = R.drawable.card7;
buttonGraphics[7] = R.drawable.card8;
buttonGraphics[8] = R.drawable.card9;
buttonGraphics[9] = R.drawable.card10;
buttonGraphics[10] = R.drawable.card11;
buttonGraphics[11] = R.drawable.card12;
buttonGraphicLocations = new int[numberOfElements];
shuffleButtonGraphics();
for(int r=0; r < numRow; r++)
{
for(int c=0; c <numColumns; c++)
{
MemoryButton tempButton = new MemoryButton(this, r, c, buttonGraphics[buttonGraphicLocations[r * numColumns + c]]);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
tempButton.setId(View.generateViewId());
}
tempButton.setOnClickListener(this);
buttons[r * numColumns + c] = tempButton;
gridLayout.addView(tempButton);
}
}
}
protected void shuffleButtonGraphics(){
Random rand = new Random();
for (int i=0; i < numberOfElements; i++)
{
buttonGraphicLocations[i] = i % (numberOfElements / 2);
}
for (int i=0; i < numberOfElements; i++)
{
int temp = buttonGraphicLocations[i];
int swapIndex = rand.nextInt(16);
buttonGraphicLocations[i] = buttonGraphicLocations[swapIndex];
buttonGraphicLocations[swapIndex] = temp;
}
}
private int buttonGraphicLocations(int i) {
return 0;
}
#Override
public void onClick(View view) {
if(isBusy) {
return;
}
MemoryButton button = (MemoryButton) view;
if(button.isMatched) {
return;
}
if(selectedButton1 == null)
{
selectedButton1 = button;
selectedButton1.flip();
return;
}
if(selectedButton1.getId()== button.getId())
{
return;
}
if (selectedButton1.getFrontDrawableId()== button.getFrontDrawableId())
{
button.flip();
button.setMatched(true);
if (selectedButton1 != null) {
selectedButton1.setEnabled(false);
System.out.println("not null");
}
else{
System.out.println("null");
}
if (selectedButton2 != null) {
selectedButton2.setEnabled(false);
System.out.println("not null");
}
else{
System.out.println("null");
}
gameStatus = gameStatus + 1;
gameScore = gameScore + 10;
if (gameStatus == 12){
Intent it = new Intent(Game6x4Activity.this, ActivityScore.class);
startActivity(it);
}
selectedButton1 = null;
return;
}
else
{
selectedButton2 = button;
selectedButton2.flip();
isBusy = true;
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run(){
selectedButton2.flip();
selectedButton1.flip();
selectedButton1 = null;
selectedButton2 = null;
isBusy = false;
}
},500);
return;
}
}
}
The activity that i want to open will show to the player his score. the activity is equal to all game modes, there will be some test to the app understant what path should go on. test like this one:
"
if (gameStatus == 12) {
gameScore = gameScore*55;
TextView scoreText = (TextView) findViewById(R.id.textView8);
scoreText.setText(gameScore);
}
else if (gameStatus == 15){
"
There are 4 game modes: This is the 6x4 game, where we can find 24 cards (12 images).
else if (gameStatus == 15){
Intent intent = new Intent(Game6x4Activity.this, NextActivity.class);
startActivity(intent);
}
I think, you are asking for this. You can pass value to another activity with
intent.putExtra("key",desired value);

calculator project app stopped while launching in phone [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
here is my code: Manifest file of my calculator project.:
When i try to launch the application on my phone which runs android 4.4.2 kitkat version , it says that calculator stopped forced close.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.jeet.calculator"
android:versionCode="1"
android:versionName="1.0">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Here is my xml code:
<?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="match_parent"
android:orientation="vertical">
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight= "30">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/textview1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_gravity="right"
android:gravity="right"
android:padding="10dp"
android:text=""/>
<TextView
android:id="#+id/textview2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_gravity="right"
android:gravity="right"
android:padding="10dp"
android:text=""
android:layout_marginBottom="10dp" />
<Button
android:id="#+id/clear"
style="?android:attr/buttonStyleSmall"
android:layout_width="260dp"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Clear"
android:layout_marginLeft="60dp" />
<LinearLayout
android:layout_width="fill_parent"
android:gravity="center"
android:layout_marginTop="10dp"
android:orientation="horizontal"
android:layout_height="wrap_content">
<Button
android:id="#+id/one"
android:layout_width="65dp"
android:layout_height="55dp"
android:text="1" />
<Button
android:id="#+id/two"
android:layout_width="65dp"
android:layout_height="55dp"
android:text="2"/>
<Button
android:id="#+id/three"
android:layout_width="65dp"
android:layout_height="55dp"
android:text="3"/>
<Button
android:id="#+id/add"
android:layout_width="65dp"
android:layout_height="55dp"
android:text="+"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<Button
android:id="#+id/four"
android:layout_width="65dp"
android:layout_height="55dp"
android:text="4"/>
<Button
android:id="#+id/five"
android:layout_width="65dp"
android:layout_height="55dp"
android:text="5"/>
<Button
android:id="#+id/six"
android:layout_width="65dp"
android:layout_height="55dp"
android:text="6"/>
<Button
android:id="#+id/minus"
android:layout_width="65dp"
android:layout_height="55dp"
android:text="-"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<Button
android:id="#+id/seven"
android:layout_width="65dp"
android:layout_height="55dp"
android:text="7"/>
<Button
android:id="#+id/eight"
android:layout_width="65dp"
android:layout_height="55dp"
android:text="8"/>
<Button
android:id="#+id/nine"
android:layout_width="65dp"
android:layout_height="55dp"
android:text="9"/>
<Button
android:id="#+id/divide"
android:layout_width="65dp"
android:layout_height="55dp"
android:text="/"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<Button
android:id="#+id/ce"
android:layout_width="65dp"
android:layout_height="55dp"
android:text="CE"/>
<Button
android:id="#+id/zero"
android:layout_width="65dp"
android:layout_height="55dp"
android:text="0"/>
<Button
android:id="#+id/equal"
android:layout_width="65dp"
android:layout_height="55dp"
android:text="="/>
<Button
android:id="#+id/mul"
android:layout_width="65dp"
android:layout_height="55dp"
android:text="*"/>
</LinearLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>
Here is the MainActivity code in Java:
package com.example.jeet.calculator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button b1, b2, b3, b4, b5, b6, b7, b8, b9, bzero, bAdd, bSub, bMul, bDiv, bClear, bEqual,bCe;
TextView txt1, txt2;
String s = "", s1 = "" , s2 = "" , resultString = "";
int i =0 , i1 = 0, c = -1;
int result = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.real);
b1 = (Button)findViewById(R.id.one);
b2 = (Button) findViewById(R.id.two);
b3 = (Button)findViewById(R.id.three);
b4 = (Button)findViewById(R.id.four);
b5 = (Button)findViewById(R.id.five);
b6 = (Button)findViewById(R.id.six);
b7 = (Button)findViewById(R.id.seven);
b8 = (Button)findViewById(R.id.eight);
b9 = (Button)findViewById(R.id.nine);
bzero = (Button)findViewById(R.id.zero);
bAdd = (Button)findViewById(R.id.add);
bSub = (Button)findViewById(R.id.minus);
bMul = (Button)findViewById(R.id.mul);
bDiv = (Button)findViewById(R.id.divide);
bClear = (Button)findViewById(R.id.clear);
bCe = (Button)findViewById(R.id.ce);
txt1 = (TextView)findViewById(R.id.textview1);
txt2 = (TextView)findViewById(R.id.textview2);
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
s = (String) txt1.getText();
if (s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")) {
txt1.setText("");
s = "";
}
txt1.setText(s + "1");
s = "";
}
});
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
s = (String) txt1.getText();
if (s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")) {
txt1.setText("");
s = "";
}
txt1.setText(s + "2");
s = "";
}
});
b3.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
s = (String)txt1.getText();
if(s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")) {
txt1.setText("");
s = "";
}
txt1.setText(s + "3");
s = "";
}
});
b4.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
s = (String)txt1.getText();
if(s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")){
txt1.setText("");
s = "";
}
txt1.setText(s + "4");
s = "";
}
});
b5.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
s = (String)txt1.getText();
if(s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")){
txt1.setText("");
s = "";
}
txt1.setText(s + "5");
s = "";
}
});
b6.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
s = (String)txt1.getText();
if(s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")){
txt1.setText("");
s = "";
}
txt1.setText(s + "6");
s = "";
}
});
b7.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
s = (String)txt1.getText();
if(s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")){
txt1.setText("");
s = "";
}
txt1.setText(s + "7");
s = "";
}
});
b8.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
s = (String)txt1.getText();
if(s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")){
txt1.setText("");
s = "";
}
txt1.setText(s + "8");
s = "";
}
});
b9.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
s = (String)txt1.getText();
if(s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")){
txt1.setText("");
s = "";
}
txt1.setText(s + "9");
s = "";
}
});
bzero.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
s = (String)txt1.getText();
if(s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")){
txt1.setText("");
s = "";
}
txt1.setText(s + "0");
s = "";
}
});
bCe.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
txt1.setText("");
txt2.setText("");
i = 0;
i1 = 0;
s1 = "";
s2 = "";
resultString = "";
c = -1;
result = 0;
}
});
bClear.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
s = (String)txt1.getText();
if(s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/") || s.equals("")){
i = 0;
}
else{
i = Integer.parseInt(s);
i = i/10;
}
if(i == 0){
txt1.setText("");
}
else{
txt1.setText(i + "");
}
s = null;
}
});
bAdd.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
String tmp = (String)txt1.getText();
if(tmp.isEmpty()){
s1 = "0";
}
else if(!tmp.equals("+") && !tmp.equals("-") && !tmp.equals("*") && !tmp.equals("/")){
s1 = tmp;
}
c = 0;
resultString = "";
txt1.setText("+");
txt2.setText(s1 + " + ");
}
});
bSub.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
String tmp = (String)txt1.getText();
if(tmp.isEmpty()){
s1 = "0";
}
else if(!tmp.equals("+") && !tmp.equals("-") && !tmp.equals("*") && !tmp.equals("/")){
s1 = tmp;
}
c= 1;
resultString = "";
txt1.setText("-");
txt2.setText(s1 + " - ");
}
});
bMul.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
String tmp = (String)txt1.getText();
if(tmp.isEmpty()){
s1 = "0";
}
else if(!tmp.equals("+") && !tmp.equals("-") && !tmp.equals("*") && !tmp.equals("/")){
s1 = tmp;
}
c= 3;
resultString = "";
txt1.setText("*");
txt2.setText(s1 + " * ");
}
});
bDiv.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
String tmp = (String)txt1.getText();
if(tmp.isEmpty()){
s1 = "0";
}
else if(!tmp.equals("+") && !tmp.equals("-") && !tmp.equals("*") && !tmp.equals("/")){
s1 = tmp;
}
c= 2;
resultString = "";
txt1.setText("/");
txt2.setText(s1 + " / ");
}
});
bEqual.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String operator = "";
if (s1.equalsIgnoreCase("+") || s1.equalsIgnoreCase("-") || s1.equalsIgnoreCase("/") || s1.equalsIgnoreCase("*")) {
i = 0;
} else if (s1 == null || s1.isEmpty()) {
i = 0;
} else {
i = Integer.parseInt(s1);
}
if(resultString.isEmpty()) {
s2 = (String) txt1.getText();
if (s2.equalsIgnoreCase("+") || s2.equalsIgnoreCase("-") || s2.equalsIgnoreCase("/") || s2.equalsIgnoreCase("*")) {
i1 = 0;
} else if (s2 == null || s2.isEmpty()) {
i1 = 0;
} else {
i1 = Integer.parseInt(s2);
}
} else {
i = result;
}
if (c == 0) {
operator = "+";
result = i + i1;
} else if (c == 1) {
operator = "-";
result = i - i1;
} else if (c == 2) {
operator = "/";
if (i1 == 0) {
Toast.makeText(getApplicationContext(),
"Invalid Input", Toast.LENGTH_LONG).show();
result = 0;
} else {
result = i / i1;
}
} else if (c == 3) {
operator = "*";
result = i * i1;
} else {
operator = "";
result = 0;
}
//History Storage
if(!operator.isEmpty()) {
txt2.setText(i + " " + operator + " " + i1);
} else {
txt2.setText("");
}
resultString = String.valueOf(result);
txt1.setText(resultString);
}
});
}
}
The Logcat error is as follows:
**02-09 23:39:17.070 766-766/com.example.jeet.calculator E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.jeet.calculator, PID: 766
java.lang.RuntimeException: Unable to start activity** ComponentInfo{com.example.jeet.calculator/com.example.jeet.calculator.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2338)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5299)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.jeet.calculator.MainActivity.onCreate(MainActivity.java:347)
at android.app.Activity.performCreate(Activity.java:5264)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2302)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321) 
at android.os.Handler.dispatchMessage(Handler.java:110) 
at android.os.Looper.loop(Looper.java:193) 
at android.app.ActivityThread.main(ActivityThread.java:5299) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645) 
at dalvik.system.NativeStart.main(Native Method) 
I'm not sure but i think you forgot to do FindViewById on bEqual

validation for empty edit text field is not working

I have two TextView, two EditText and two Buttons. I want to set a DialogBox or Toast when the button is clicked without entering any values in the textview. I have two stings, s and s1. If s and s1 or either s or s1 is not entered in the edittext, I must get a toast. I wrote a code for toast but it's not working fine!
Can you help me with this?
This is my code:
public class MainActivity extends Activity implements OnClickListener {
TextView name1;
TextView name2;
Button click;
Button samegender;
EditText boyname;
EditText girlname;
ImageView imgview;
AnimationDrawable frameanimation;
Bitmap bmp;
String bread;
String cheese;
char sauce;
MediaPlayer song;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//fullscreen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow(). setFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN , WindowManager LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
name1 = (TextView) findViewById(R.id.tvname1);
name2 = (TextView) findViewById(R.id.tvname2);
click = (Button) findViewById(R.id.btclick);
samegender=(Button) findViewById(R.id.btsamegender);
samegender.setOnClickListener(this);
boyname = (EditText) findViewById(R.id.etboyname);
boyname.setInputType(InputType.TYPE_CLASS_TEXT);
girlname = (EditText) findViewById(R.id.etgirlname);
girlname.setInputType(InputType.TYPE_CLASS_TEXT);
imgview=(ImageView)findViewById(R.id.imageanim);
imgview.setBackgroundResource(R.drawable.myanim);
frameanimation=(AnimationDrawable) imgview.getBackground();
frameanimation.start();
click.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btclick:
DataInputStream dis = new DataInputStream(System.in);
int i,
j = 0;
int d = 0;
int totlen;
String flames;
int[] newarr = new int[20];
int[] newarr1 = new int[20];
System.out.println("enter name");
String s = boyname.getText().toString();
StringBuffer sb = new StringBuffer(s);
char namearr[] = s.toCharArray();
System.out.println("enter name");
String s1 = girlname.getText().toString();
//code for toast//
//if s nd s1 is empty then execute this else executee the rest//
if((s==" ") && (s1==" "))
{
Toast.makeText(getBaseContext(),"cnt b empty" ,Toast.LENGTH_SHORT). show();
}
else
{
StringBuffer sb1 = new StringBuffer(s1);
System.out.println("the string1=" + s);
System.out.println("the string2=" + s1);
char namearr1[] = s1.toCharArray();
try {
for (i = 0; i < sb.length(); i++) {
for (j = 0, d = 0; j < sb1.length(); j++) {
if (sb.charAt(i) == sb1.charAt(j)) {
sb.deleteCharAt(i);
System.out.println("the buff=" + sb);
sb1.deleteCharAt(j);
System.out.println("the buff=" + sb1);
i = 0;
break;
}
}
}
} catch (Exception e) {
System.out.println(e);
}
sb.length();
System.out.println("string length=" + sb.length());
sb1.length();
System.out.println("string length=" + sb1.length());
int len = sb.length() + sb1.length();
totlen = len - 1;
System.out.println("string length=" + totlen);
String str = "flames";
StringBuffer sb2 = new StringBuffer(str);
int index = 0;
str.length();
int length = str.length();
System.out.println("the length of flames is=" + str.length());
while (index < length) {
char letter = str.charAt(index);
System.out.println(letter);
index = index + 1;
}
System.out.println(sb2.length());
int m = 0,
n = 0;
for (m = 0;;) {
if (n == totlen) {
sb2.deleteCharAt(m);
System.out.println(sb2 + " m:" + m + " n:" + n);
System.out.println(sb2);
n = 0;
m--;
} else {
n++;
}
if (m == sb2.length() - 1) {
m = 0;
} else {
m++;
}
if (sb2.length() == 1) {
break;
}
}
char res = sb2.charAt(0);
System.out.println("the final char is=" + res);
String bread = boyname.getText().toString();
String cheese = girlname.getText().toString();
char sauce = res;
Bundle basket = new Bundle();
basket.putString("name1", bread);
basket.putString("name2", cheese);
basket.putChar("ans", sauce);
Intent a = new Intent(MainActivity.this, ResultActivity.class);
a.putExtras(basket);
startActivity(a);
}
break;
Change your validation to this :
if((s.equals("")) && (s1.equals("")))
{
Toast.makeText(getBaseContext(),"cnt b empty" ,Toast.LENGTH_SHORT).show();
}
Or you can check like this:
if((s.length() == 0) && (s1.length() == 0))
{
Toast.makeText(getBaseContext(),"cnt b empty" ,Toast.LENGTH_SHORT). show();
}
Tried your code and validation is working :
import java.io.DataInputStream;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
TextView name1;
TextView name2;
Button click;
Button samegender;
EditText boyname;
EditText girlname;
ImageView imgview;
Bitmap bmp;
String bread;
String cheese;
char sauce;
MediaPlayer song;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// fullscreen
requestWindowFeature(Window.FEATURE_NO_TITLE);
// getWindow(). setFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN
// ,WindowManager LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
name1 = (TextView) findViewById(R.id.tvname1);
name2 = (TextView) findViewById(R.id.tvname2);
click = (Button) findViewById(R.id.btclick);
samegender = (Button) findViewById(R.id.btsamegender);
samegender.setOnClickListener(this);
boyname = (EditText) findViewById(R.id.etboyname);
boyname.setInputType(InputType.TYPE_CLASS_TEXT);
girlname = (EditText) findViewById(R.id.etgirlname);
girlname.setInputType(InputType.TYPE_CLASS_TEXT);
imgview = (ImageView) findViewById(R.id.imageanim);
frameanimation = (AnimationDrawable) imgview.getBackground();
frameanimation.start();
click.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btclick:
DataInputStream dis = new DataInputStream(System.in);
int i,
j = 0;
int d = 0;
int totlen;
String flames;
int[] newarr = new int[20];
int[] newarr1 = new int[20];
System.out.println("enter name");
String s = boyname.getText().toString();
StringBuffer sb = new StringBuffer(s);
char namearr[] = s.toCharArray();
System.out.println("enter name");
String s1 = girlname.getText().toString();
// code for toast//
// if s nd s1 is empty then execute this else executee the rest//
if ((s.equals("")) || (s1.equals(""))) {
Toast.makeText(getBaseContext(), "cnt b empty",
Toast.LENGTH_SHORT).show();
} else {
StringBuffer sb1 = new StringBuffer(s1);
System.out.println("the string1=" + s);
System.out.println("the string2=" + s1);
char namearr1[] = s1.toCharArray();
try {
for (i = 0; i < sb.length(); i++) {
for (j = 0, d = 0; j < sb1.length(); j++) {
if (sb.charAt(i) == sb1.charAt(j)) {
sb.deleteCharAt(i);
System.out.println("the buff=" + sb);
sb1.deleteCharAt(j);
System.out.println("the buff=" + sb1);
i = 0;
break;
}
}
}
} catch (Exception e) {
System.out.println(e);
}
sb.length();
System.out.println("string length=" + sb.length());
sb1.length();
System.out.println("string length=" + sb1.length());
int len = sb.length() + sb1.length();
totlen = len - 1;
System.out.println("string length=" + totlen);
String str = "flames";
StringBuffer sb2 = new StringBuffer(str);
int index = 0;
str.length();
int length = str.length();
System.out.println("the length of flames is=" + str.length());
while (index < length) {
char letter = str.charAt(index);
System.out.println(letter);
index = index + 1;
}
System.out.println(sb2.length());
int m = 0, n = 0;
for (m = 0;;) {
if (n == totlen) {
sb2.deleteCharAt(m);
System.out.println(sb2 + " m:" + m + " n:" + n);
System.out.println(sb2);
n = 0;
m--;
} else {
n++;
}
if (m == sb2.length() - 1) {
m = 0;
} else {
m++;
}
if (sb2.length() == 1) {
break;
}
}
char res = sb2.charAt(0);
System.out.println("the final char is=" + res);
String bread = boyname.getText().toString();
String cheese = girlname.getText().toString();
char sauce = res;
Bundle basket = new Bundle();
basket.putString("name1", bread);
basket.putString("name2", cheese);
basket.putChar("ans", sauce);
Intent a = new Intent(MainActivity.this, ResultActivity.class);
a.putExtras(basket);
startActivity(a);
}
break;
}
}
}
Try if (s.isEmpty() || s1.isEmpty()) to check if your strings are empty. == and .equals will not work with string comparison because they are comparing the objects and not solely the contents. To check if two strings are equal, you can use firstString.compareTo(anotherString) == 0.
Trim your edittext value then compare
if((("").equals(s.trim())) && (("").equals(s1.trim())))
{
Toast.makeText(getBaseContext(),"cnt b empty" ,Toast.LENGTH_SHORT).show();
}

Android Layout help needed

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.

Categories

Resources