how to scrumble the word if i click a button - java

How can I make a button that scrambles the letter every time I click it? When I try to make another button and then click it, it will scramble the letter. Then, when I got another word, when I clicked again on the scramble button, it was back to the first word I answered. (I'm just new. I'm sorry for my code).
public static String wordJumble(String word )
{
Random random = new Random();
char wordArray[] = word.toCharArray();
for(int i=0; i< wordArray.length; i++ )
{
int j = random.nextInt(wordArray.length);
char temp = wordArray[i];
wordArray[i] = wordArray[j];
wordArray[j] = temp;
}
if(wordArray.toString().equals(word)){
wordJumble(word);
}
return new String(wordArray);
}
#Override
protected void onResume() {
super.onResume();
final String [] str=quesWord.toArray(new String[quesWord.size()]);
attemptsLeft.setText("Attempts left: "+chances);
points.setText("Score: "+score);
jumbleWord.setText(wordJumble(str[0]));
b.setOnClickListener(new OnClickListener() {
int j=0;
int len=str.length;
#Override
public void onClick(View v) {
try{
if(answerText.getText().toString().trim().equalsIgnoreCase(str[j])){
score++;
if(score==len){
dbHandler.addScore2("JL",score);
countDownTimer.cancel();
adb.setTitle("You Won!");
adb.setMessage("Score: "+score);
adb.setPositiveButton("Okay", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
adb.show();
}
j++;
points.setText("Score: "+score);
jumbleWord.setText((wordJumble(str[j])));
}
My shuffle Button
shuffle.setOnClickListener(new View.OnClickListener() {
int j=0;
#Override
public void onClick(View v) {
j++;
jumbleWord.setText((wordJumble(str[j])));
}
});

Related

Get string line by line android programmatically

I have this code but the problem is that this continually showing toast of each string line when I pressed my desired button.
Like this:
Clicked the button once:
Toast shows continually:
A
B
C
What I want is to get string from a single line once I click the button.
Like this:
EditText value:
A
B
C
Result first click:
A only
Result second click:
B only
Result third click:
C only
Like that
Btw this is the code I use:
Button checkButton = (Button) findViewById(R.id.check_Button);
checkButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText editBox = (EditText) findViewById(R.id.edit_Text);
String items = editBox.getText().toString();
Scanner scanner = new Scanner(items);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
Toast.makeText(getApplicationContext(), line, Toast.LENGTH_SHORT).show();
}
scanner.close();
}
}
);
I know it's hard to understand but please bare with me.
I think you can go for an approach like this.
int clicks = 0;
Button checkButton = (Button) findViewById(R.id.check_Button);
checkButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText editBox = (EditText) findViewById(R.id.edit_Text);
String items = editBox.getText().toString();
if (i == 0) {
Toast.makeText(getApplicationContext(), items , Toast.LENGTH_LONG).show();
i++;
editBox.setText("");
} else if (i == 1) {
Toast.makeText(getApplicationContext(), items , Toast.LENGTH_LONG).show();
i++;
editBox.setText("");
} else if (i==2) {
Toast.makeText(getApplicationContext(), items , Toast.LENGTH_LONG).show();
i = 0;
}
}
}
Just enter a value in the editText when the value is reset after a single button click.
int position=0;
EditText editText=findViewById(R.id.editText);
editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable editable) {
}
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
if(charSequence.length()<=0)
{
position=-1;
}
else{
position=0;
}
}
});
Button button=findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
int length=editText.getText().length();
if(position==-1){
Toast.makeText(getApplicationContext(),"Nothing in EditText box",Toast.LENGTH_LONG).show();
return;
}
if(position==length){
position=0;
}
Toast.makeText(getApplicationContext(),editText.getText().charAt(position),Toast.LENGTH_LONG).show();
position++;
}
});

Java_after popup error,layout is freezing and doesn't working

I making android application,I need error popup in one moment and when popup is showing and I click OK,popup is closing but main layout is dark and doesn't work,it is freezing.
please see my code,Can I refresh or reactivate this layout?
I need any solution for this.
please help and thank you
package com.example.granturismo.binaryconverter;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.calculate:
try {
EditText decimal = findViewById(R.id.decimal_value);
EditText binary = findViewById(R.id.binary);
Dialog dlg = new Dialog(this);
dlg.setCancelable(false);
dlg.setTitle("Please Input Any Number");
dlg.show();
int decimal_value = Integer.parseInt(decimal.getText().toString());
List<Integer> binary_nums = new ArrayList<Integer>();
String result = "";
int nashti = 1;
for (int i = decimal_value; i >= 2; ) {
binary_nums.add((i % 2));
i = i / 2;
nashti = i;
}
binary_nums.add((nashti % 2));
for (int i = 0; i < binary_nums.size(); i++) {
result += "" + binary_nums.get(i);
}
binary.setText(new StringBuilder(result).reverse().toString());
}
catch(Exception e){
AlertDialog.Builder alert=new AlertDialog.Builder(this);
alert.setTitle("Error");
alert.setMessage("Please Input Any Number");
alert.setCancelable(true);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
}).show();
}
break;
case R.id.clear:
EditText decimal1=findViewById(R.id.decimal_value);
EditText binary1=findViewById(R.id.binary);
decimal1.setText("");
binary1.setText("");
break;
case R.id.shecvla:
Button shecvla=(Button) findViewById(R.id.shecvla);
TextView convertSign=(TextView) findViewById(R.id.convertSign);
if(shecvla.getText()==getString(R.string.dectobin)) {
shecvla.setText(getString(R.string.dectobin));
convertSign.setText(R.string.bintodec);
}
else{
shecvla.setText(getString(R.string.bintodec));
convertSign.setText(R.string.dectobin);
}
break;
}
}
}

Application Crashed when trying to input on an edittext that has an TextChangedListener

I was trying to create an application that automatically calculate the percentage. the Percentage value will be shown in a TextView. The value that will be shown in the textview will be based on the inputted value of the user in an edittext.
I've finished creating my codes for this program but, it keeps crashing every time i tried to input some numbers in the edittext.
I hope you understand what am i saying.
Here is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample__table);
btnAdd = (Button)findViewById(R.id.btnAdd);
//btn Function
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AddRow();
}
});
//end of btn function
//text changed
tl = (TableLayout) findViewById(R.id.tl);
row = new TableRow(this);
TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
row.setLayoutParams(lp);
fruit = new EditText(this);
freq = new EditText(this);
perc = new TextView(this);
freq.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
ReCalculate();
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
});
//text changed end
}
private void AddRow(){
row.addView(fruit);
row.addView(freq);
row.addView(perc);
tl.addView(row);
}
private void ReCalculate(){
float sum = 0f;
int rows = tl.getChildCount();
// Get the total
for (int i = 0; i < rows; i++) {
TableRow elem = (TableRow) tl.getChildAt(i);
sum+= Integer.parseInt(((EditText)elem.getChildAt(1)).getText().toString());
}
// Recalculate every row percent
for (int i = 0; i < rows; i++) {
TableRow elem = (TableRow) tl.getChildAt(i);
int amount​ = Integer.parseInt(((TextView)elem.getChildAt(1)).getText().toString());
((TextView)elem.getChildAt(1)).setText(String.valueOf(amount​/sum*100));
}
}
}
If you want to detect your text's change, you can use onKeyListener:
EditText edtText = (EditText)findViewById(R.id.editText);
edtText.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View view, int i, KeyEvent keyEvent) {
Toast.makeText(MainActivity.this, "Text changed!", Toast.LENGTH_SHORT).show();
return false;
}
});
it worked for me, hope it helps.

How to calculate reaction time?

I have developed an app that has two buttons (left and right) and a Textview that will pop up on the screen.Each button has it's corresponding word.
The user has to click the button that corresponds to TextView's word as quickly as possible when it shows. I want to calculate it's reaction time on clicking the button.
Below is my code.
public class Place_to_go_1 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_place_to_go_1);
placeone = Global_variables.getFirst_choice_label();
placetwo = Global_variables.getSecond_choice_label();
p_one = (TextView)findViewById(R.id.p_one);
p_two = (TextView)findViewById(R.id.p_two);
btnleft = (ImageButton)findViewById(R.id.btnleft);
btnright = (ImageButton)findViewById(R.id.btnright);
next = (ImageButton)findViewById(R.id.Next);
lblmaintext = (TextView)findViewById(R.id.lblmaintext);
lblprompt = (TextView)findViewById(R.id.lblprompt);
lblreact = (TextView)findViewById(R.id.lblreact);
imgmain = (ImageView)findViewById(R.id.imgmain);
//prac = (ImageView) findViewById(R.id.prac);
Intent intent = getIntent();
final String randomId = intent.getStringExtra("Info_id");
//============ validate image if not empty
setImage_onLaunch();
//==== populate left and right choices===
populate_headers(placeone, placetwo);
//==== populate attributes=====
populate_attributes();
//============== instruction ======
setInstruction();
//=============media
wrong_press = MediaPlayer.create(this, R.raw.wrong_press);
react_fast = MediaPlayer.create(this, R.raw.react_faster);
//=== left button click trigger
btnleft.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String position = "H";
if (tanan[counter].equals(p_one.getText().toString())) {
lblprompt.setVisibility(View.INVISIBLE);
HashMap<String,String> queryValues = new HashMap<String, String>();
queryValues.put("Info_id",randomId);
queryValues.put("Choice",p_one.getText().toString());
queryValues.put("Reaction_time",String.valueOf(elapsedTime));
queryValues.put("Position",position);
queryValues.put("Main",main);
queryValues.put("Error",error);
mydb.insertTest(queryValues);
counter++;
if (counter < tanan.length) {
btnleft.setEnabled(false);
btnright.setEnabled(false);
timeStamp = System.currentTimeMillis();
//Toast.makeText(Place_to_go_1.this, ""+timeStamp, Toast.LENGTH_SHORT).show();
getreactionTime(p_one.getText().toString(), String.valueOf((((timeStamp) / 1000.0) - ((timeRun) / 1000.0))));
setIntervalTime();
} else {
//======end sa data
postEnd();
}
} else {
// Toast.makeText(Place_to_go_1.this, "Wrong pressed", Toast.LENGTH_SHORT).show();
//wrong_press.start();
wrong_click_audio();
error = "1";
lblprompt.setVisibility(View.VISIBLE);
}
}
});
//==== right button click trigger
btnright.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String position = "A";
if (tanan[counter].equals(p_two.getText().toString())) {
lblprompt.setVisibility(View.INVISIBLE);
HashMap<String,String> queryValues = new HashMap<String, String>();
queryValues.put("Info_id",randomId);
queryValues.put("Choice",p_two.getText().toString());
queryValues.put("Reaction_time", String.valueOf(elapsedTime));
queryValues.put("Position",position);
queryValues.put("Main",main);
queryValues.put("Error",error);
mydb.insertTest(queryValues);
counter++;
if (counter < tanan.length) {
btnleft.setEnabled(false);
btnright.setEnabled(false);
timeStamp = System.currentTimeMillis();
//Toast.makeText(Place_to_go_1.this, ""+timeStamp, Toast.LENGTH_SHORT).show();
getreactionTime(p_two.getText().toString(), String.valueOf((((timeStamp) / 1000.0) - ((timeRun) / 1000.0))));
setIntervalTime();
} else {
//======end sa data
postEnd();
}
} else {
// Toast.makeText(Place_to_go_1.this, "Wrong pressed", Toast.LENGTH_SHORT).show();
// wrong_press.start();
wrong_click_audio();
error = "1";
lblprompt.setVisibility(View.VISIBLE);
}
}
});
// ==== next button for the next activity (Place to go 2)
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = getIntent();
String randomId = intent.getStringExtra("Info_id");
//============= launch activity 2 for place to go
if (instruct == true) {
next.setVisibility(View.INVISIBLE);
// prac.setVisibility(View.VISIBLE);
CountDownTimer();
} else {
//Toast.makeText(getApplication(),"Saved Successfully.",Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), Place_to_go_2.class);
i.putExtra("Info_id", randomId);
startActivity(i);
}
}
});
}
public void interval(){
if(counter < tanan.length){
lblmaintext.setVisibility(View.VISIBLE);
timeRun = System.currentTimeMillis();
btnleft.setEnabled(true);
btnright.setEnabled(true);
lblmaintext.setText(tanan[counter]);
setImage();
imgmain.setVisibility(View.VISIBLE);
react = true;
reacFaster();
}else{
//======end sa data
Toast.makeText(Place_to_go_1.this, "End data", Toast.LENGTH_SHORT).show();
lblmaintext.setVisibility(View.VISIBLE);
lblmaintext.setText("Ok for now");
}
}
public void setIntervalTime(){
react = false;
lblreact.setVisibility(View.INVISIBLE);
reactFaster_timer.cancel();
lblmaintext.setVisibility(View.INVISIBLE);
lblreact.setVisibility(View.INVISIBLE);
imgmain.setVisibility(View.INVISIBLE);
timer = new CountDownTimer(Global_variables.interval_time_before_choices_will_show,Global_variables.interval_time_before_choices_will_show) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
interval();
}
}.start();
}
int counter_countdown = 0;
int drawwable_amber = R.drawable.amber;
String arr[] = {"Ready...","Set...","Start."};
public void CountDownTimer(){
btnleft.setVisibility(View.INVISIBLE);
btnright.setVisibility(View.INVISIBLE);
lblmaintext.setBackgroundResource(0);
timer = new CountDownTimer(4000,1000) {
#Override
public void onTick(long millisUntilFinished) {
lblmaintext.setTextSize(35);
lblmaintext.setText(arr[counter_countdown]);
counter_countdown++;
}
#Override
public void onFinish() {
btnleft.setVisibility(View.VISIBLE);
btnright.setVisibility(View.VISIBLE);
lblmaintext.setBackgroundResource(drawwable_amber);
// lblmaintext.setText(tanan[counter]);
//setImage();
val_first_launch();
timeRun = System.currentTimeMillis();
react = true;
reacFaster();
}
}.start();
}
public void reacFaster(){
reactFaster_timer = new CountDownTimer(Global_variables.reaction_time_first_param,Global_variables.reaction_time_second_param) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
if(react == true){
//Toast.makeText(Place_to_go_1.this, "please react faster", Toast.LENGTH_SHORT).show();
react_fast.start();
lblreact.setVisibility(View.VISIBLE);
}
}
}.start();
}
public void populate_headers(String one,String two){
//== this methos sets headers as random==//
headers = new ArrayList<String>();
headers.add(one);
headers.add(two);
Collections.shuffle(headers);
p_one.setText(headers.get(0));
p_two.setText(headers.get(1));
}
public void populate_attributes(){
attributes = new ArrayList<String>();
for(int h =0;h < 5;h++){
attributes.add(placeone);
attributes.add(placetwo);
}
Collections.shuffle(attributes);
tanan = new String[attributes.size()];
for(int k = 0; k < tanan.length;k++ ){
tanan[k] = attributes.get(k);
}
}
public void postEnd(){
instruct = false;
lblprompt.setVisibility(View.INVISIBLE);
btnright.setVisibility(View.INVISIBLE);
btnleft.setVisibility(View.INVISIBLE);
next.setVisibility(View.VISIBLE);
lblmaintext.setBackgroundResource(0);
lblmaintext.setTextSize(20);
p_one.setVisibility(View.INVISIBLE);
p_two.setVisibility(View.INVISIBLE);
imgmain.setVisibility(View.INVISIBLE);
reactFaster_timer.cancel();
lblreact.setVisibility(View.INVISIBLE);
lblmaintext.setText("Well done!\nNext, is the main task. It is exactly the same as before but this time words will appear on the screen that might distract you. \nPlease respond as quickly as you can.\n Press Next to begin");
}
//=========== validate if image is enabled/ disble if not set
public void setImage_onLaunch(){
if(Global_variables.getFirst_choice_image().equals("") || Global_variables.getSecond_choice_image().equals("")){
disbaleImage();
}else{
}
}
public void setImage(){
/* if(tanan[counter].equals(p_one.getText().toString())){
imgmain.setImageBitmap(BitmapFactory.decodeFile(Global_variables.getFirst_choice_image()));
}else{
imgmain.setImageBitmap(BitmapFactory.decodeFile(Global_variables.getSecond_choice_image()));
}*/
if(placeone.equals(tanan[counter])){
imgmain.setImageBitmap(BitmapFactory.decodeFile(Global_variables.getFirst_choice_image()));
}else{
imgmain.setImageBitmap(BitmapFactory.decodeFile(Global_variables.getSecond_choice_image()));
}
}
public void val_first_launch(){
if(Global_variables.getFirst_choice_image().equals("") || Global_variables.getSecond_choice_image().equals("")){
lblmaintext.setVisibility(View.VISIBLE);
lblmaintext.setText(tanan[counter]);
}else{
imgmain.setVisibility(View.VISIBLE);
if(placeone.equals(tanan[counter])){
imgmain.setImageBitmap(BitmapFactory.decodeFile(Global_variables.getFirst_choice_image()));
}else{
imgmain.setImageBitmap(BitmapFactory.decodeFile(Global_variables.getSecond_choice_image()));
}
}
}
public void disbaleImage(){
imgmain.setBackgroundResource(0);
imgmain.setVisibility(View.GONE);
}
#Override
public void onBackPressed() {
super.onBackPressed();
startActivity(new Intent(getApplication(), MainActivity.class));
finish();
}
public String getreactionTime(String domain, String time){
// Toast.makeText(Place_to_go_1.this, time, Toast.LENGTH_SHORT).show();
//== get reaction time to every activity
Global_variables.set_timeStamps(domain, time);
return domain;
}
//===== prompt instruction====
public void setInstruction(){
btnleft.setVisibility(View.INVISIBLE);
btnright.setVisibility(View.INVISIBLE);
lblmaintext.setBackgroundResource(0);
lblmaintext.setTextSize(20);
lblmaintext.setText("Instruction:\n\nIf " + p_one.getText().toString() + " appears, press arrow left.\n If " + p_two.getText().toString() +
" appears, press arrow right.\n\nRespond as quickly as you can.");
next.setVisibility(View.VISIBLE);
}
//===== prompt instruction====
public void wrong_click_audio(){
wrong_press.start();
}
//=============end class====================
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
// Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
//Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
}
}
Here a simple logic to calculate reaction time is to create a variable which hold a time when a question is popped up to user and the time when a user show a click reaction to question and calculate the time difference between these two action.
long timeWhenQuestionShowed = System.currentTimeMillis();
long timeWhenUserReacted = System.currentTimeMillis();
long reactionTime = timeWhenQuestionShowed - timeWhenUserReacted;
This should help:
Try using onTouch instead of onClick.
long timeBefor=0;
long timeReaction=0;
btnleft.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: // when pressed
timeBefore=System.currentTimeMillis();
break;
case MotionEvent.ACTION_UP: // when released
timeReaction=System.currentTimeMillis() - timeBefore; // calculate difference
break;
}
}
timeReaction is your desired value.
The idea is to calculate the difference between 2 points in time. I will write 2 examples of calculating time difference in Java / measuring reaction time in Java:
System.nanoTime() or System.currentTimeMillis()
Differences are discussed here: Time measuring overhead in Java
long endTimeNanoSec = 0;
long startTimeNanoSec = System.nanoTime();
myWorkThatNeedsTiming(); // wait for user button press here
endTimeNanoSec = System.nanoTime();
long totalWorkTimeNanos = endTimeNanoSec - startTimeNanoSec;
Java StopWatch
JavaDoc: StopWatch
Stopwatch stopwatch = Stopwatch.createStarted();
myWorkThatNeedsTiming(); // wait for user button press here
stopwatch.stop();
long totalWorkTimeMillis = stopwatch.elapsedMillis();

validation according to data types

want to validate edit text according to SQLite table data types
I have one table in my SQLite database which has three data types integer,integer,text respectively. edit texts are creates dynamically according to columns present in table. now I want to give validation on each text box like if I enter string value for integer datatype then one popup should display which shows message "can't insert text value for data type integer". so what can I do now?
here is my code
public class DisplayTable_Grid extends Activity
{
TableLayout table_layout;
SQL_crud sqlcon;
TableRow rw;
TextView gettxt_onLongclik;
ArrayList<String> storeColumnNames;
EditText enter_text;
TextView set_txt;
List<EditText> allEds = new ArrayList<EditText>();
ArrayList<String> storeallEds=new ArrayList<String>();
ArrayList<String> storeEditextText=new ArrayList<String>();
List<TextView> textViewlst = new ArrayList<TextView>();
ArrayList<String> getColumnNames=new ArrayList<String>();
ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.displaytable);
sqlcon = new SQL_crud(this);
table_layout = (TableLayout) findViewById(R.id.diplay_table);
BuildTable();
}
private void BuildTable()
{
sqlcon.open();
storeColumnNames=sqlcon.getColumnNames(DisaplayTables_list.getTableNameFromListView.toString());
Cursor c = sqlcon.readEntryofTable(DisaplayTables_list.getTableNameFromListView.toString());
int rows = c.getCount();
int cols = c.getColumnCount();
String colN=c.getColumnNames().toString();
arraylist=sqlcon.readColumn_Datatypes(DisaplayTables_list.getTableNameFromListView.toString ());
ArrayList<String> colName=new ArrayList<String>();
colName=sqlcon.getColumnNames(DisaplayTables_list.getTableNameFromListView.toString());
//colName.add(colN);
c.moveToFirst();
System.out.println("size of hash map:"+arraylist.size());
for(int k=0;k<1;k++)
{
TableRow rowcolumnName = new TableRow(this);
rowcolumnName.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
rowcolumnName.setBackgroundColor(Color.GRAY);
for(int a=0;a<cols/*arraylist.size()*/;a++)
{
TextView columnName = new TextView(this);
columnName.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
columnName.setGravity(Gravity.CENTER);
columnName.setTextSize(18);
columnName.setPadding(0, 5, 0, 5);
columnName.setText(colName.get(a)+" "+arraylist.get(a).toString());
rowcolumnName.addView(columnName);}
table_layout.addView(rowcolumnName);
// c.moveToNext();
}
// outer for loop
if(rows==0)
{
Toast.makeText(getApplicationContext(), "rows not found..cant build table", Toast.LENGTH_LONG);
}
else{
for (int i = 0; i < rows; i++)
{
TableRow row = new TableRow(this);
row.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
// inner for loop
for (int j = 0; j < cols; j++)
{
TextView tv = new TextView(this);
tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
tv.setGravity(Gravity.CENTER);
tv.setTextSize(18);
tv.setPadding(0, 5, 0, 5);
tv.setText(c.getString(j));
row.addView(tv);
}
row.setClickable(true);
row.requestFocus();
row.setOnLongClickListener(new OnLongClickListener()
{
#Override
public boolean onLongClick(View viewlong)
{
rw=(TableRow) viewlong;
gettxt_onLongclik=(TextView)rw.getChildAt(0);
Toast.makeText(getApplicationContext(),gettxt_onLongclik.getText().toString(),Toast.LENGTH_SHORT).show();
final AlertDialog.Builder alertForSelectOperation=new AlertDialog.Builder(DisplayTable_Grid.this);
final LinearLayout linear=new LinearLayout(DisplayTable_Grid.this);
linear.setOrientation(LinearLayout.VERTICAL);
//TextView update=(TextView)new TextView(DisplayTable_Grid.this);
Button update=(Button)new Button(DisplayTable_Grid.this);
//update.setBackgroundColor(Color.rgb(3,12,90));
update.setText(Html.fromHtml("<font size=10>Update</font>"));
update.setOnClickListener(new OnClickListener()
{ #Override
public void onClick(View arg0)
{
final AlertDialog.Builder alertDialogOK_CANCEL=new AlertDialog.Builder(DisplayTable_Grid.this);
final LinearLayout linearlayout=new LinearLayout(DisplayTable_Grid.this);
linearlayout.setOrientation(LinearLayout.VERTICAL);
sqlcon.open();
getColumnNames=sqlcon.getColumnNames(DisaplayTables_list.getTableNameFromListView.toString());
Cursor crs=sqlcon.readColumnCnt(DisaplayTables_list.getTableNameFromListView.toString());
int count=crs.getColumnCount();
Cursor cr=sqlcon.getSinlgeEntryof_table(DisaplayTables_list.getTableNameFromListView.toString(),getColumnNames.get(0), gettxt_onLongclik.getText().toString());
cr.moveToFirst();
for(int i=0;i<count;i++)
{ //add edittext to arralist
enter_text=new EditText(DisplayTable_Grid.this);
allEds.add(enter_text);
allEds.get(i).setText(cr.getString(cr.getColumnIndex(getColumnNames.get(i))));
linearlayout.addView(enter_text);
}
sqlcon.close();
//finish();
alertDialogOK_CANCEL.setPositiveButton("Update", new DialogInterface.OnClickListener()
{ #Override
public void onClick(DialogInterface arg0, int arg1)
{
for(int i=0;i<allEds.size();i++)
{
//System.out.println(allEds.get(i).getText().toString());
storeallEds.add(allEds.get(i).getText().toString());
String getarraylist=arraylist.get(i).toString();
String datatype_text="{datatype=text}";
String datatype_integer="{datatype=integer}";
if(getarraylist.equals(datatype_text) || getarraylist.equals(datatype_integer))
{
if(getarraylist.equals(datatype_text))
{
Toast.makeText(getApplicationContext(), "text"+storeallEds.get(i),Toast.LENGTH_LONG).show();
//enter_text.setInputType(InputType.TYPE_CLASS_TEXT);
}
else if(getarraylist.equals(datatype_integer))
{
if(storeallEds.get(i).contains("a"))//allEds.get(i).getText().toString().contains("a")||allEds.get(i).getText().toString().contains("b"))
{
Toast.makeText(getApplicationContext(), "String in integer value",Toast.LENGTH_LONG).show();
//enter_text.setInputType(InputType.TYPE_CLASS_NUMBER);
}
else
{
//storeallEds.add(allEds.get(i).getText().toString());
Toast.makeText(getApplicationContext(), "integer"+storeallEds.get(i),Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(getApplicationContext(), "no datatype found",Toast.LENGTH_LONG).show();
}
}
}
//System.out.println(storeallEds);
sqlcon.open();
try
{
sqlcon.updateRecord(DisaplayTables_list.getTableNameFromListView.toString(), gettxt_onLongclik.getText().toString(), storeallEds);
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(),"Can't Update column already exists ",Toast.LENGTH_LONG).show();
}
Intent i=new Intent(getApplicationContext(),DisplayTable_Grid.class);
startActivity(i);
sqlcon.close();
}
});
alertDialogOK_CANCEL.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{ #Override
public void onClick(DialogInterface dialog, int arg1)
{
dialog.dismiss();
}
});
alertDialogOK_CANCEL.setView(linearlayout);
alertDialogOK_CANCEL.setTitle("insert values here");
alertDialogOK_CANCEL.create();
alertDialogOK_CANCEL.show();
}
});
//TextView delete=(TextView)new TextView(DisplayTable_Grid.this);
Button delete=(Button)new Button(DisplayTable_Grid.this);
delete.setText(Html.fromHtml("<font size=10> Delete</font>"));
//delete.setBackgroundColor(Color.rgb(3,12,90));
delete.setOnClickListener(new OnClickListener()
{ #Override
public void onClick(View arg0)
{
final AlertDialog.Builder alertDialogOK_CANCEL=new AlertDialog.Builder(DisplayTable_Grid.this);
alertDialogOK_CANCEL.setMessage("Press OK to Delete this Record");
alertDialogOK_CANCEL.setPositiveButton("OK", new DialogInterface.OnClickListener()
{ #Override
public void onClick(DialogInterface arg0, int arg1)
{
sqlcon.open();
sqlcon.deleteEntry(DisaplayTables_list.getTableNameFromListView, storeColumnNames.get(0), gettxt_onLongclik.getText().toString());
sqlcon.close();
Intent i=new Intent(getApplicationContext(),DisplayTable_Grid.class);
startActivity(i);
}
});
alertDialogOK_CANCEL.setNegativeButton("CANCEL",new DialogInterface.OnClickListener()
{ #Override
public void onClick(DialogInterface dialog, int arg1)
{
dialog.dismiss();
}
});
alertDialogOK_CANCEL.create();
alertDialogOK_CANCEL.show();
}
});
//TextView insert=(TextView)new TextView(DisplayTable_Grid.this);
Button insert=(Button)new Button(DisplayTable_Grid.this);
insert.setText(Html.fromHtml("<font size=10>Insert</font>"));
//insert.setBackgroundColor(Color.rgb(3,12,90));
insert.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
final AlertDialog.Builder alertDialog=new AlertDialog.Builder(DisplayTable_Grid.this);
final LinearLayout linearlayout=new LinearLayout(DisplayTable_Grid.this);
linearlayout.setOrientation(LinearLayout.VERTICAL);
sqlcon.open();
getColumnNames=sqlcon.getColumnNames(DisaplayTables_list.getTableNameFromListView);
Cursor crs=sqlcon.readColumnCnt(DisaplayTables_list.getTableNameFromListView);
int count=crs.getColumnCount();
for(int i=0;i<count;i++)
{ //add edittext to arralist
enter_text=new EditText(DisplayTable_Grid.this);
allEds.add(enter_text);
String getarraylist=arraylist.get(i).toString();
String datatype_text="{datatype=text}";
String datatype_integer="{datatype=integer}";
if(getarraylist.equals(datatype_text))
{
Toast.makeText(getApplicationContext(), "text",Toast.LENGTH_LONG).show();
enter_text.setInputType(InputType.TYPE_CLASS_TEXT);
}
else if(getarraylist.equals(datatype_integer))
{
Toast.makeText(getApplicationContext(), "integer",Toast.LENGTH_LONG).show();
//enter_text.setInputType(InputType.TYPE_CLASS_NUMBER);
}
else
{
Toast.makeText(getApplicationContext(), "no datatype found",Toast.LENGTH_LONG).show();
}
//add textview to ayyalist
set_txt=new TextView(DisplayTable_Grid.this);
set_txt.setText(getColumnNames.get(i));
set_txt.setTextSize(15);
textViewlst.add(set_txt);
linearlayout.addView(set_txt);
linearlayout.addView(enter_text);
}
sqlcon.close();
alertDialog.setPositiveButton("Insert", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface arg0, int arg1)
{
if(allEds.size()==0)
{Toast.makeText(getApplicationContext(), "value not found",Toast.LENGTH_LONG).show();}
else
{
for(int i=0; i < allEds.size(); i++)
{ storeEditextText.add(allEds.get(i).getText().toString());
System.out.println("show gettext: "+storeEditextText.get(i).toString());
String getarraylist=arraylist.get(i).toString();
String datatype_text="{datatype=text}";
String datatype_integer="{datatype=integer}";
if(getarraylist.equals(datatype_text))
{
Toast.makeText(getApplicationContext(), "text",Toast.LENGTH_LONG).show();
}
else if(getarraylist.equals(datatype_integer))
{
Toast.makeText(getApplicationContext(), "integer",Toast.LENGTH_LONG).show();
if(storeEditextText.contains("a")||storeEditextText.contains("b"))
{
try
{
int edittxtint=Integer.parseInt(allEds.get(i).getText().toString());//enter_text.setInputType(InputType.TYPE_CLASS_NUMBER);
}
catch(Exception e)
{
System.out.println("exception....."+e);
Toast.makeText(getApplicationContext(),"value must be an integer",Toast.LENGTH_LONG).show();
}
}
}
else
{
Toast.makeText(getApplicationContext(), "no datatype found",Toast.LENGTH_LONG).show();
}
}
if(storeEditextText.size()==0)
{Toast.makeText(getApplicationContext(), "Text is empty",Toast.LENGTH_LONG).show();}
else
{
sqlcon.open();
try
{sqlcon.insert(DisaplayTables_list.getTableNameFromListView,storeEditextText);}
catch(Exception e)
{Toast.makeText(getApplicationContext(),"emp_id is Primary key", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(),"column value already exists",Toast.LENGTH_LONG).show();}
System.out.println("size of storeEdittext="+storeEditextText.size());
System.out.println("size of Edit Texts: "+allEds.size());
}
Intent i=new Intent(getApplicationContext(),DisplayTable_Grid.class);
startActivity(i);
sqlcon.close();
}
}
});
alertDialog.setView(linearlayout);
alertDialog.setTitle("insert values here");
alertDialog.create();
alertDialog.show();
}
});
linear.addView(insert);
linear.addView(update);
linear.addView(delete);
alertForSelectOperation.setView(linear);
alertForSelectOperation.setTitle("perform operations here");
alertForSelectOperation.create();
alertForSelectOperation.show();
alertForSelectOperation.setCancelable(true);
return false;
}
});
row.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
TableRow rw=(TableRow) v;
TextView gettxt=(TextView)rw.getChildAt(0);
Toast.makeText(getApplicationContext(), gettxt.getText().toString(),Toast.LENGTH_SHORT).show();
}
});
c.moveToNext();
table_layout.addView(row);
}
}//end of else for null rows
sqlcon.close();
}
}
You can modify your table definition and add "CHECK" constraint, like this:
CREATE TABLE tab (
column1 INTEGER CHECK(typeof(column1) == "integer"),
column2 INTEGER CHECK(typeof(column2) == "integer"),
column3 TEXT CHECK(typeof(column3) == "text")
);
This will enable your database to enforce datatype checking for this table. This will slow down the insertions/updates on this table just a bit.

Categories