Android: Activity loop causes ad to refresh - android

In my Android Quiz app i've implemented Admob. But everytime an Answer is given and the Questions changes, Admob refreshes, too, which takes about 3-4 seconds. But by that time the Question changes again and so on.
QuestionActivity.class:
package com.tsc.walkingdead;
import java.util.List;
import com.google.ads.*;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import com.tsc.walkingdead.R;
import com.tsc.walkingdead.quiz.GamePlay;
import com.tsc.walkingdead.quiz.Question;
import com.tsc.walkingdead.util.Utility;
public class QuestionActivity extends Activity implements OnClickListener{
private Question currentQ;
private GamePlay currentGame;
;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.question);
// Look up the AdView as a resource and load a request.
AdView adView = (AdView)this.findViewById(R.id.adView);
adView.loadAd(new AdRequest());
/**
* Configure current game and get question
*/
currentGame = ((WalkingDeadApplication)getApplication()).getCurrentGame();
currentQ = currentGame.getNextQuestion();
Button nextBtn = (Button) findViewById(R.id.nextBtn);
nextBtn.setOnClickListener(this);
/**
* Update the question and answer options..
*/
setQuestions();
}
/**
* Method to set the text for the question and answers from the current games
* current question
*/
private void setQuestions() {
//set the question text from current question
String question = Utility.capitalise(currentQ.getQuestion()) + "??";
TextView qText = (TextView) findViewById(R.id.question);
qText.setText(question);
//set the available options
List<String> answers = currentQ.getQuestionOptions();
TextView option1 = (TextView) findViewById(R.id.answer1);
option1.setText(Utility.capitalise(answers.get(0)));
TextView option2 = (TextView) findViewById(R.id.answer2);
option2.setText(Utility.capitalise(answers.get(1)));
TextView option3 = (TextView) findViewById(R.id.answer3);
option3.setText(Utility.capitalise(answers.get(2)));
TextView option4 = (TextView) findViewById(R.id.answer4);
option4.setText(Utility.capitalise(answers.get(3)));
}
#Override
public void onClick(View arg0) {
//Log.d("Questions", "Moving to next question");
/**
* validate a checkbox has been selected
*/
if (!checkAnswer()) return;
/**
* check if end of game
*/
if (currentGame.isGameOver()){
Intent i = new Intent(this, EndgameActivity.class);
startActivity(i);
finish();
}
else{
Intent i = new Intent(this, QuestionActivity.class);
startActivity(i);
finish();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
switch (keyCode)
{
case KeyEvent.KEYCODE_BACK :
return true;
}
return super.onKeyDown(keyCode, event);
}
/**
* Check if a checkbox has been selected, and if it
* has then check if its correct and update gamescore
*/
private boolean checkAnswer() {
String answer = getSelectedAnswer();
if (answer==null){
//Log.d("Questions", "No Checkbox selection made - returning");
return false;
}
else {
//Log.d("Questions", "Valid Checkbox selection made - check if correct");
if (currentQ.getAnswer().equalsIgnoreCase(answer))
{
//Log.d("Questions", "Correct Answer!");
currentGame.incrementRightAnswers();
Toast.makeText(this, "Correct!", Toast.LENGTH_LONG).show();
}
else{
//Log.d("Questions", "Incorrect Answer!");
currentGame.incrementWrongAnswers();
Toast.makeText(this, "Wrong!", Toast.LENGTH_LONG).show();
}
return true;
}
}
/**
*
*/
private String getSelectedAnswer() {
RadioButton c1 = (RadioButton)findViewById(R.id.answer1);
RadioButton c2 = (RadioButton)findViewById(R.id.answer2);
RadioButton c3 = (RadioButton)findViewById(R.id.answer3);
RadioButton c4 = (RadioButton)findViewById(R.id.answer4);
if (c1.isChecked())
{
return c1.getText().toString();
}
if (c2.isChecked())
{
return c2.getText().toString();
}
if (c3.isChecked())
{
return c3.getText().toString();
}
if (c4.isChecked())
{
return c4.getText().toString();
}
return null;
}
}
question.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/walking_dead_background2"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:gravity="center"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center">
<RadioGroup
android:id="#+id/group1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center_vertical">
<TextView
android:id="#+id/question"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="#style/myStyle1"
android:layout_marginBottom="10dp"/>
<RadioButton
android:id="#+id/answer1"
android:checked="false"
style="#style/myStyle"/>
<RadioButton
android:id="#+id/answer2"
android:checked="false"
style="#style/myStyle"/>
<RadioButton
android:id="#+id/answer3"
android:checked="false"
style="#style/myStyle"/>
<RadioButton
android:id="#+id/answer4"
android:checked="false"
style="#style/myStyle"/>
<Button
android:id="#+id/nextBtn"
style="#style/myStyle"
android:layout_width="80dip"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="#drawable/button_selector"
android:paddingBottom="5dip"
android:paddingTop="5dip"
android:text="Next"
android:textColor="#ffffff" />
</RadioGroup>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="bottom"
android:id="#+id/mainLayout">
<com.google.ads.AdView android:id="#+id/adView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
ads:adUnitId="ca-app-pub-6195077402939893/2503837566"
ads:adSize="BANNER"
ads:testDevices="TEST_EMULATOR"/>
</LinearLayout>
</LinearLayout>
Is it possible to let the Ad show the whole time, though the questions are changing?
Thank you

Your problem is that you are starting a new Activity in #onClick.
Don't start a new Activity, reuse the current Activity.
In this case somethig like:
#Override
public void onClick(View arg0) {
//Log.d("Questions", "Moving to next question");
/**
* validate a checkbox has been selected
*/
if (!checkAnswer()) return;
/**
* check if end of game
*/
if (currentGame.isGameOver()){
Intent i = new Intent(this, EndgameActivity.class);
startActivity(i);
finish();
}
else{
currentQ = currentGame.getNextQuestion();
setQuestions();
}
}

Try removing
adView.loadAd(new AdRequest());
from your onCreate and adding
ads:loadAdOnCreate="true"
to your ads XML.

Related

How to keep state of RadioButton in Android?

Hi I'm trying to develop an application which runs for every interval time, lets say for every 1 minute it will display some Toast message.
But problem is I'm using RadioButton functionality is perfect but when I tap on one radio button it will be green, but when I close and re-open the activity I'll get as none of the radio buttons selected.
Here is my MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio_one_min:
if (checked)
{
//some code
}
break;
case R.id.radio_ten_min:
if (checked)
{
//some code
}
break;
case R.id.radio_disable:
if (checked)
{
//some code
}
break;
}
}
}
and here is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/radio">
<RadioButton android:id="#+id/radio_disable"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Disable"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/radio_one_min"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1 minute"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/radio_ten_min"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="10 minute"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
Please help me to solve this riddle.
Thanks in advance...
This code is useful for store the ratingbar state, when we start new activity, you will see the previous rating state..
package com.example.ratingbar;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
public class RatingbarMainActivity extends Activity {
RatingBar ratingbarClick;
Button sub_btn;
TextView textRatingView , textRatingViewSave;
Boolean val = true;
float ans = (float) 0.0;
//--------------------------------------------------------------------------------------------
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ratingbar_main);
ratingbarClick = (RatingBar) findViewById(R.id.ratingBar1);
ratingbarClick.setOnRatingBarChangeListener(rateObj);
SharedPreferences sharePref = PreferenceManager.getDefaultSharedPreferences
(RatingbarMainActivity.this);
ans = sharePref.getFloat("Get_Rating", 0.0f);
System.out.println("--------------------------------------ans = " + ans);
if(val) {
ratingbarClick.setRating(ans);
}
else {
ratingbarClick.setRating(ans);
}
textRatingView = (TextView) findViewById(R.id.ratingView);
}
//--------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
RatingBar.OnRatingBarChangeListener rateObj = new RatingBar.OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar, float rating,boolean fromUser) {
//textRatingView.setText(String.valueOf(rating));
ans = ratingbarClick.getRating();
SharedPreferences sharePref = PreferenceManager.getDefaultSharedPreferences
(RatingbarMainActivity.this);
SharedPreferences.Editor edit = sharePref.edit();
edit.putFloat("Get_Rating", ans);
edit.commit();
val = false;
}
};
//--------------------------------------------------------------------------------------------
}
---------------------------------------------------------------------------------------------------
activity_ratingbar_main.xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
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:layout_alignLeft="#+id/ratingBar1"
android:layout_alignParentTop="true"
android:layout_marginLeft="15dp"
android:layout_marginTop="23dp"
android:text="Select Your Rating Bar Here"
tools:context=".RatingbarMainActivity" />
<RatingBar
android:id="#+id/ratingBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="21dp"
android:layout_marginTop="63dp" />
<TextView
android:id="#+id/ratingView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/ratingBar1"
android:text="TextView" />
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Click To Save Rating In TextBox" />
</RelativeLayout>
it is the simplest way to do so,no need of sharedpreference at all.you will get confused while using it.keep the things simple like this
public class MainActivity extends Activity {
Public static int flag=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(flag==1)
radio_one_min.setChecked(true);
else if(flag==2)
radio_ten_min.setCheckek(true);
else if(flag==3)
radio_disable.setCheckek(true);
}
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio_one_min:
if (checked)
{
flag =1;
//some code
}
break;
case R.id.radio_ten_min:
if (checked)
{
flag=2 ;
//some code
}
break;
case R.id.radio_disable:
if (checked)
{
flag=3;
//some code
}
break;
}
}
}
[EDITED]
I found developer.android.com/training/basics/activity-lifecycle/recreating.html document first, so my first guess was using Bundles and on Save/Resume Instace State methods. However this does not seem to work well. Here's my final attempt at a working solution (using SharedPreferences class, as suggested by some users):
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
public class MainActivity extends Activity {
final String PREFERENCES = "prefs";
final String RADIO_BUTTON = "prefsval";
SharedPreferences sp;
Editor e;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp = this.getSharedPreferences(PREFERENCES, MODE_PRIVATE);
e = sp.edit();
}
#Override
protected void onResume() {
super.onResume();
if (sp != null) {
if (sp.getInt(RADIO_BUTTON, 0) != 0) {
RadioButton rb;
rb = (RadioButton) findViewById(sp.getInt(RADIO_BUTTON, 0));
rb.setChecked(true);
}
}
}
public void onRadioButtonClicked(View view) {
e.putInt(RADIO_BUTTON, view.getId());
e.apply();
}
}

Android onclick Buttons Sequence

I have 5 buttons every one has letter (Button "H",Button "E"Button "L"Button "L"Button "O") which make the word "HELLO". what I need is to make on click sequence to these buttons so if I click "H" first and "E" second until complete the word the app will do something, But if I click "L" first will give me some error message.
Any Idea to do this sequence?
Thanks
Just have an Array like this:
int[] tracker = new int[5];
and when you click a button, say "H", set tracker[0] = 1;
but when you click a button, say "L", check whether all the previous button values are 1. If yes, then set the corresponding tracker to 1 else, show an error message, and do not make any change to the tracker Array.
Something Like this:
onHClick{
tracker[0] = 1;
}
onEClick{
for(int i=0; i<1; i++){
if(tracker[i] == 0){
//show error message and return;
}else{
tracker[1] = 1;
return;
}
}
}
You can do something like
When activity started you just make other button Enabled = false of something like that. But make the first button Enabled. Don't make the Visible=false.
Now on click of Button "H" make enable Button "E" and so on.
So user will only have to click the button in sequence. Button can not be presses in any random manner.
Try this and let me know that it works or not.
Very Interesting and exactly same to your requirement..check once..
If you give any string other than HELLO also works better.
public class ButtonTest extends Activity
{
private String result="";
String sampleText = "HELLO";
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
int noOfBtns = sampleText.length();
LinearLayout ll = (LinearLayout)findViewById(R.id.btnlay);
final TextView tvtext = (TextView)findViewById(R.id.result);
final Button[] btns = new Button[noOfBtns];
for(int i=0;i<noOfBtns;i++)
{
btns[i] = new Button(this);
btns[i].setText(sampleText.substring(i,i+1));
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ll.addView(btns[i], lp);
final int j = i;
btns[i].setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
System.out.println(j+" "+result.length());
if(j == result.length())
{
result = result+btns[j].getText().toString();
if(sampleText.startsWith(result))
{
tvtext.setText(result);
}
}
else
{
Toast.makeText(getApplicationContext(), "Wrong Button Pressed", Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
Layout file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/result"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:textColor="#fff"/>
<LinearLayout
android:id="#+id/btnlay"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
</LinearLayout>
</LinearLayout>
Try the following
package com.example.buttonsequence;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity
{
ArrayList<Button> buttonList=null;
TextView resultTextView=null;
Button buttons[]=null;
String helloStr="HELLO";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonList=new ArrayList<Button>();
buttons=new Button[5];
this.resultTextView=(TextView) this.findViewById(R.id.result_text);
this.resultTextView.setText("");
buttons[0]=(Button)this.findViewById(R.id.h_button);
buttons[1]=(Button)this.findViewById(R.id.e_button);
buttons[2]=(Button)this.findViewById(R.id.l_button);
buttons[3]=(Button)this.findViewById(R.id.l2_button);
buttons[4]=(Button)this.findViewById(R.id.o_button);
for(int k=0;k<5;k++)
buttons[k].setOnClickListener(onClickListener);
Button button=(Button)this.findViewById(R.id.exit_button);
button.setOnClickListener
(
new OnClickListener()
{
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
}
);
}
OnClickListener onClickListener=new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Button b=(Button)v;
buttonList.add(b);
int size=buttonList.size();
if(size>0)
{
StringBuilder resultBuilder=new StringBuilder();
for(int i=0;i<size;i++)
{
Button tempButton=buttonList.get(i);
if(tempButton==buttons[i])
{
resultBuilder.append(helloStr.charAt(i));
if(i==4)
{
resultTextView.setText(resultBuilder.toString()+" clicked");
buttonList.clear();
}
else
{
resultTextView.setText(resultBuilder.toString()+" clicked");
}
}
else
{
buttonList.remove(i);
Toast.makeText(getApplicationContext(), "No correctly clicked", Toast.LENGTH_SHORT).show();
break;
}
}
}
else
{
resultTextView.setText("Invalid pressed");
}
}
};
}
activity_main.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<Button
android:id="#+id/h_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="H" />
<Button
android:id="#+id/e_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="E" />
<Button
android:id="#+id/l_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="L" />
<Button
android:id="#+id/l2_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="L" />
<Button
android:id="#+id/o_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="O" />
<TextView
android:id="#+id/result_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
<Button
android:id="#+id/exit_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Exit" />
</LinearLayout>
I don't know exactly your flow but you can try this.
set Tag to each button as its Text, like this.
b.setTag("H");
and than after like this.
Button b;
String name = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s = (String) v.getTag();
name +=s;
if( "HELLO".startsWith(name)){
<VALID>
}else{
<ERROR>
}
}
});
}
check the variable name on each button click with your original word i.e. HELLO like above.

I want to show my login form in dialog box or in pop up box using android

I have two textViews in one xml ie. Customer login and Suppliers login...When i am clicking on cuztomer login or suppliers login pop up should open on that I want to show my login form.
Help me out please.
Here is my login form:login_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/background"
android:orientation="vertical" >
<include layout="#layout/header_layout" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_margin="10dip"
android:orientation="vertical" >
<TextView
android:id="#+id/lbl_username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dip"
android:gravity="center"
android:textColor="#000000"
android:text="#string/username"
/>
<EditText
android:id="#+id/et_username"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:hint="#string/enter_username"
android:inputType="textEmailAddress" />
<TextView
android:id="#+id/lbl_password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="15dip"
android:gravity="center"
android:textColor="#000000"
android:text="#string/password"
/>
<EditText
android:id="#+id/et_password"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:hint="#string/enter_password"
android:inputType="textPassword"
android:singleLine="true" />
<TextView
android:id="#+id/lbl_forgot"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dip"
android:gravity="center"
android:textColor="#000000"
android:text="#string/forgot_password"
android:textSize="18dp"
/>
<Button
android:id="#+id/loginButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="15dip"
android:text="#string/login"
/>
</LinearLayout>
</LinearLayout>
Here is LoginActivity.java:
package com.Login;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
public class LoginActivity extends Activity {
private EditText etUsername, etPassword;
private Button loginButton;
private JSONParser jsonParser;
private static String loginURL = "http://www.xyz.com?login.php";
private Bundle bundle;
private String success;
/** The dialog. */
private ProgressDialog dialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_layout);
TextView textv = (TextView) findViewById(R.id.lbl_forgot);
textv.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setClass(v.getContext(), ForgotPassActivity.class);
startActivity(intent);
}
});
intitDisplay();
addListeners();
}
private void addListeners() {
loginButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (etUsername.getText().length() == 0)
etUsername.setError("please enter username");
if (etPassword.getText().length() == 0)
etPassword.setError("please enter password");
if ((etUsername.getText().length() > 0)
&& (etPassword.getText().length() > 0)) {
jsonParser = new JSONParser();
if (jsonParser.isNetworkAvailable(LoginActivity.this)) {
new BackgroundTask().execute();
} else {
Toast.makeText(LoginActivity.this,
"Network not available", Toast.LENGTH_LONG)
.show();
}
}
}
});
}
private void intitDisplay() {
etUsername = (EditText) findViewById(R.id.et_username);
etPassword = (EditText) findViewById(R.id.et_password);
loginButton = (Button) findViewById(R.id.loginButton);
bundle = new Bundle();
dialog = new ProgressDialog(LoginActivity.this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.login_layout, menu);
return true;
}
/** calling web service to get creditors list */
/**
* The Class BackgroundTask.
*/
private class BackgroundTask extends AsyncTask<String, Void, String> {
/** The resp. */
String resp;
/*
* (non-Javadoc)
*
* #see android.os.AsyncTask#onPreExecute()
*/
protected void onPreExecute() {
dialog.setMessage("Loading...");
dialog.setCancelable(false);
dialog.show();
}
/*
* (non-Javadoc)
*
* #see android.os.AsyncTask#doInBackground(Params[])
*/
protected String doInBackground(final String... args) {
Log.v("ENTERED USERNAME::", "" + etUsername.getText().toString());
String newUrl = loginURL + "username="
+ etUsername.getText().toString() + "&password="
+ etPassword.getText().toString();
JSONObject json = jsonParser.getJSONFromUrl(newUrl);
try {
success = json.getString("msg");
Log.v("SUCCESS:: ", success);
if (success.trim().toString().equalsIgnoreCase("SUCCESS")) {
String loggedUsername = json.getString("USER_NAME");
bundle.putString("loggedUser", loggedUsername);
Log.v("Logged User::", loggedUsername);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/*
* (non-Javadoc)
*
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
protected void onPostExecute(String list) {
dialog.dismiss();
if (success.trim().toString().equalsIgnoreCase("SUCCESS")) {
Toast.makeText(LoginActivity.this, "Login Succesfull..",
Toast.LENGTH_LONG).show();
Intent intent = new Intent(LoginActivity.this,
HomeActivity.class).putExtras(bundle);
startActivity(intent);
} else {
Toast.makeText(LoginActivity.this, "Login failed...",
Toast.LENGTH_LONG).show();
}
}
}
}
Use this
Create a new xml file which has the textfields,edittexts,buttons i.e. your login form that you want to show in the popup.Now call the following method where you want to show the popup.
private void callLoginDialog()
{
myDialog = new Dialog(this);
myDialog.setContentView(R.layout.yourxmlfileID);
myDialog.setCancelable(false);
Button login = (Button) myDialog.findViewById(R.id.yourloginbtnID);
emailaddr = (EditText) myDialog.findViewById(R.id.youremailID);
password = (EditText) myDialog.findViewById(R.id.yourpasswordID);
myDialog.show();
login.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
//your login calculation goes here
}
});
}
Let me know if it helps you....
Apply #android:style/Theme.Dialog to your login activity. You can do that in the Manifest editor.
In your manifest file give like this
<activity android:name=".LoginActivity"
android:label="Login"
android:theme="#style/CustomDialogTheme"
android:configChanges="locale|keyboardHidden|orientation"/>
and in styles.xml give the customDialogTheme as
<style name="CustomDialogTheme" parent="#android:style/Theme.Dialog">
<item name="android:bottomBright">#fff</item>
<item name="android:bottomDark">#fff</item>
<item name="android:bottomMedium">#fff</item>
<item name="android:centerBright">#fff</item>
<item name="android:centerDark">#fff</item>
<item name="android:centerMedium">#fff</item>
<item name="android:fullBright">#7D266A</item>
<item name="android:fullDark">#7D266A</item>
<item name="android:topBright">#2f6699</item>
<item name="android:topDark"#2f6699</item>
</style>
Use custom dialog.
create layouts for Customer and Suppliers
Show custom dialog dialog on click according to your requirement.
Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.customerlogin);
or
dialog.setContentView(R.layout.supplierlogin);
dialog.show();

Android error on change layout in same activity

I'm developing an android application. It is an exam app. When a user clicks an answer, the application changes the layout with $setContentView(); in same activity.
But it gives an error for layout Caused by: java.lang.NumberFormatException: unable to parse '#2131230721' as integer
My layout file is below, if you need I can put my project myserver. And I can paste my activity code, but it's a basic setContentView() only. I guess one of my id's is causing the error but i couldn't find it.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#fff"
android:orientation="vertical"
android:weightSum="1" >
<LinearLayout
android:id="#+id/soruNoIleriVeGeri"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.01"
android:weightSum="1" >
<LinearLayout
android:id="#+id/SoruLayout"
android:layout_width="fill_parent"
android:layout_height="60dp"
android:background="#drawable/question_top_plain"
android:weightSum="1" >
<LinearLayout
android:id="#+id/OncekiSoru"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageButton
android:id="#+id/qIPrevious"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/back_button"
android:onClick="qIPrevious"
android:paddingLeft="5dp" />
</LinearLayout>
<LinearLayout
android:layout_width="57dp"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/about_question" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent" >
<ImageButton
android:id="#+id/ImageButton01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/add_favourite" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/goToQuestion"
android:layout_width="56dp"
android:layout_height="wrap_content"
android:onClick="onshowQuestion"
android:src="#drawable/show_question" />
</LinearLayout>
<LinearLayout
android:layout_width="50dp"
android:layout_height="45dp"
android:layout_weight="0.57" >
<ImageButton
android:id="#+id/homeButton"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/tab_home"
android:onClick="goHome" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent" >
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/next_button"
android:onClick="qINextQuestion" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/question_top_plain"
android:weightSum="1" >
<LinearLayout
android:id="#+id/resultIconPlain"
android:layout_width="84dp"
android:layout_height="fill_parent"
android:paddingLeft="20dp" >
</LinearLayout>
<LinearLayout
android:layout_width="234dp"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/resultView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1.13"
android:gravity="center_horizontal"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#111" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="59dp"
android:background="#drawable/question_top_plain" >
<LinearLayout
android:id="#+id/dogruCevap"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.01"
android:weightSum="1" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/StatikDogruCevap"
android:layout_width="126dp"
android:layout_height="wrap_content"
android:text="#string/StatikDogruCevap"
android:textStyle="#style/boldText" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="0.01" >
<TextView
android:id="#+id/dogruCevapView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:paddingRight="10dp"
android:text="TextView"
android:textStyle="#style/rightAnswer" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/cevabiniz"
android:layout_width="fill_parent"
android:layout_height="54dp"
android:layout_weight="0.01"
android:weightSum="1" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/cevabinizView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:paddingLeft="10dp"
android:text="TextView"
android:textStyle="#style/rightAnswer" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/StatikCevap"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/StatikCevap"
android:textStyle="#style/boldText" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<ScrollView
android:id="#+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="350px"
android:fillViewport="true" >
<LinearLayout
android:id="#+id/dogruCevapAyrinti"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.60"
android:isScrollContainer="true"
android:minHeight="400px"
android:scrollbarAlwaysDrawHorizontalTrack="true"
android:scrollbars="vertical" >
<TextView
android:id="#+id/dogruCevapAyrintiView"
android:layout_width="fill_parent"
android:layout_height="324dp"
android:scrollHorizontally="false"
android:scrollbarAlwaysDrawHorizontalTrack="true"
android:scrollbars="vertical"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#111" >
</TextView>
</LinearLayout>
</ScrollView>
</LinearLayout>
Here is error codes and myActivity sorry for Turkish variable names
at android.app.Activity.dispatchTouchEvent(Activity.java:2061)
at
com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1643)
at android.view.ViewRoot.handleMessage(ViewRoot.java:1691)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4363)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
at dalvik.system.NativeStart.main(Native Method)
java.lang.reflect.InvocationTargetException
at android.widget.TextView.<init>(TextView.java:320)
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:446)
at android.view.LayoutInflater.createView(LayoutInflater.java:500)
... 41 more
java.lang.NumberFormatException: unable to parse '#2131230721' as integer
at java.lang.Integer.parse(Integer.java:374)
at java.lang.Integer.parseInt(Integer.java:363)
at com.android.internal.util.XmlUtils.convertValueToInt(XmlUtils.java:121)
at android.content.res.TypedArray.getInt(TypedArray.java:201)
at android.widget.TextView.<init>(TextView.java:647)
package com.eandroid.workingSet;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.eandroid.entity.Question;
public class QuestionInterfaceActivity extends Activity {
LinearLayout layoutForA;
LinearLayout layoutForB;
LinearLayout layoutForC;
LinearLayout layoutForD;
LinearLayout layoutForE;
LinearLayout choiceATotalPlain;
LinearLayout choiceBTotalPlain;
LinearLayout choiceCTotalPlain;
LinearLayout choiceDTotalPlain;
LinearLayout choiceETotalPlain;
LinearLayout allTotalPlain;
List<Question> questionList = new ArrayList<Question>();
Node node = null;
NodeList nodeList = null;
NodeList nodeListForTestInfo = null;
InputStream is = null;
private TextView choiceA;
private TextView choiceB;
private TextView choiceC;
private TextView choiceD;
private TextView choiceE;
private TextView questionText;
private TextView soruIdText;
private TextView soruIdEv;
private TextView soruBilgileriView;
private TextView cevabinizView;
private TextView dogruCevapView;
private TextView dogruCevapAyrintiView;
private TextView resultView;
private int currentQuestionIndex;
Question currentQuestion = null;
private String testName = null;
HttpClient httpclient;
HttpPost httppost;
ArrayList<NameValuePair> postParameters;
HttpResponse response;
InputStream contentStream;
private String rightAnswers = "";
private String userAnswers = "";
private String resultOfAnswers = "";
private String userId = "1";
private static String testRelationId;
private LinearLayout resultIconPlain;
private static String willPostUrl =
"http://balabanhafriyat.com/SchoolProjectWebSide/postFromPhone/SendDataFromPhone";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
Toast.makeText(QuestionInterfaceActivity.this, "Hoşgeldin Hacı",
Toast.LENGTH_SHORT).show();
}
settleOrientation();
Bundle extras = getIntent().getExtras();
if (extras != null) {
testName = extras.getString("testName");
}
try {
is = getAssets().open(testName);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(is));
doc.getDocumentElement().normalize();
nodeList = doc.getElementsByTagName("question");
nodeListForTestInfo = doc.getElementsByTagName("testInfo");
Node testNode = nodeListForTestInfo.item(0);
testRelationId = parseItToStringByName(testNode, "testRelationId");
} catch (Exception e) {
e.printStackTrace();
}
currentQuestionIndex = 1;
showQuestion();
}
public void settleOrientation() {
int setLayout = getResources().getConfiguration().orientation;
switch (setLayout) {
case 1:
setContentView(R.layout.buttontry);
loadDesign();
break;
case 2:
setContentView(R.layout.buttontry);
break;
default:
break;
}
}
public void callEvaluationActivity(int optionToSeeQuestion,
String userAnswer) {
setContentView(R.layout.evaluation_screen);
// resultView = (TextView) findViewById(R.id.resultView);
cevabinizView = (TextView) findViewById(R.id.cevabiniz);
dogruCevapView = (TextView) findViewById(R.id.rightAnswer);
dogruCevapAyrintiView = (TextView)
findViewById(R.id.dogruCevapAyrintiView);
// soruBilgileriView.setText(currentQuestion.getShortInfo());
dogruCevapAyrintiView.setText(currentQuestion.getRightAnswerDetail());
dogruCevapView.setText(currentQuestion.getRightAnswer());
if (optionToSeeQuestion == 2) {
cevabinizView.setText(userAnswer);
if (currentQuestion.getRightAnswer().equals(userAnswer)) {
resultView.setTextColor(Color.GREEN);
resultView.setText("Doğru Cevap");
resultOfAnswers = resultOfAnswers + "1$";
} else {
resultView.setTextColor(Color.RED);
resultView.setText("Cevap Yanlış !!! ");
resultOfAnswers = resultOfAnswers + "0$";
}
userAnswers = userAnswers + userAnswer + "$";
rightAnswers = rightAnswers + currentQuestion.getRightAnswer()
+ "$";
}
}
public void loadDesign() {
allTotalPlain = (LinearLayout) findViewById(R.id.allTotalPlain);
allTotalPlain.setBackgroundResource(R.drawable.yellow_button);
choiceATotalPlain = (LinearLayout) findViewById(R.id.choiceTotalPlain);
choiceBTotalPlain = (LinearLayout) findViewById(R.id.choiceBTotalPlain);
choiceCTotalPlain = (LinearLayout) findViewById(R.id.choiceCTotalPlain);
choiceDTotalPlain = (LinearLayout) findViewById(R.id.choiceDTotalPlain);
choiceETotalPlain = (LinearLayout) findViewById(R.id.choiceETotalPlain);
layoutForA = (LinearLayout) findViewById(R.id.abuttonLayout);
layoutForB = (LinearLayout) findViewById(R.id.bButtonLayout);
layoutForC = (LinearLayout) findViewById(R.id.cButtonLayout);
layoutForD = (LinearLayout) findViewById(R.id.dButtonLayout);
layoutForE = (LinearLayout) findViewById(R.id.ebuttonLayout);
createButton("A");
createButton("B");
createButton("C");
createButton("D");
createButton("E");
}
private void showQuestion() {
questionText = (TextView) findViewById(R.id.soruTextView);
choiceA = (TextView) findViewById(R.id.choiceA);
choiceB = (TextView) findViewById(R.id.choiceB);
choiceC = (TextView) findViewById(R.id.choiceC);
choiceD = (TextView) findViewById(R.id.choiceD);
choiceE = (TextView) findViewById(R.id.choiceE);
currentQuestion = setQuestionFieldById(currentQuestionIndex);
questionText.setText(currentQuestion.getQuestionText());
choiceA.setText(currentQuestion.getChoiceA());
choiceB.setText(currentQuestion.getChoiceB());
choiceC.setText(currentQuestion.getChoiceC());
choiceD.setText(currentQuestion.getChoiceD());
choiceE.setText(currentQuestion.getChoiceE());
/*
* consumerAnswer .setOnCheckedChangeListener(new
* OnCheckedChangeListener() { public void onCheckedChanged(RadioGroup
* group, int checkedId) { if (choiceA.getId() == checkedId) {
* approveAnswer(2, "A"); } if (choiceB.getId() == checkedId) {
*
* approveAnswer(2, "B"); } if (choiceC.getId() == checkedId) {
*
* approveAnswer(2, "C"); } if (choiceD.getId() == checkedId) {
*
* approveAnswer(2, "D"); } if (choiceE.getId() == checkedId) {
*
* approveAnswer(2, "E"); } } });
*/
}
private void approveAnswer(int optionToSeeQuestion, final String userChoice) {
callEvaluationActivity(optionToSeeQuestion, userChoice);
}
// Eger optionToSeeQuestion 1 ise kullanıcının cevap karsılastırılması
// yapılmamalı 2 ise yapılmalı
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == 999) {
if (data.hasExtra("action")) {
String aim = data.getExtras().getString("aim");
Toast.makeText(this, "Ne yapmak istiyorsunuz" + aim,
Toast.LENGTH_LONG).show();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public void qINextQuestion(View view) {
if (currentQuestionIndex == nodeList.getLength() - 1) {
Toast.makeText(QuestionInterfaceActivity.this, "Son Sorudasınız",
Toast.LENGTH_SHORT).show();
} else {
currentQuestionIndex++;
settleOrientation();
showQuestion();
}
}
public void qIPrevious(View view) {
if (currentQuestionIndex == 1) {
Toast.makeText(QuestionInterfaceActivity.this, "İlk Sorudasınız",
Toast.LENGTH_SHORT).show();
} else {
currentQuestionIndex--;
settleOrientation();
showQuestion();
}
}
public Question setQuestionFieldById(int questionId) {
Question q = new Question();
for (int i = 0; i < nodeList.getLength(); i++) {
node = nodeList.item(i);
int idFromXml = Integer.parseInt(parseItToStringByName(node,
"questionNumber"));
if (questionId == idFromXml) {
q.setQuestionId(questionId);
q.setChoiceA(parseItToStringByName(node, "choiceA"));
q.setChoiceB(parseItToStringByName(node, "choiceB"));
q.setChoiceC(parseItToStringByName(node, "choiceC"));
q.setChoiceD(parseItToStringByName(node, "choiceD"));
q.setChoiceE(parseItToStringByName(node, "choiceE"));
q.setQuestionText(parseItToStringByName(node,
"questionText"));
q.setRightAnswer(parseItToStringByName(node,
"rightAnswer"));
q.setRightAnswerDetail(parseItToStringByName(node,
"answerDetail"));
}
}
return q;
}
public String parseItToStringByName(Node node, String nodeName) {
Element mainELement = (Element) node;
NodeList questionList = mainELement.getElementsByTagName(nodeName);
Element questionElement = (Element) questionList.item(0);
NodeList question = questionElement.getChildNodes();
String result = question.item(0).getNodeValue().replaceAll("\n", "")
.replaceAll("\t", "");
result.trim();
return result;
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
setContentView(R.layout.landscapequestion);
showQuestion();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
setContentView(R.layout.buttontry);
showQuestion();
}
}
#Override
public void onBackPressed() {
beforeQuitProcess();
super.onBackPressed();
}
public void beforeQuitProcess() {
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("testId", testRelationId));
postParameters
.add(new BasicNameValuePair("rightAnswers", rightAnswers));
postParameters.add(new BasicNameValuePair("userAnswers", userAnswers));
postParameters.add(new BasicNameValuePair("userAnswerAndResult",
resultOfAnswers));
postParameters.add(new BasicNameValuePair("userId", userId));
PostDataToServer postDataToServer = new PostDataToServer();
HttpResponse response = postDataToServer.postData(willPostUrl,
postParameters);
contentStream = postDataToServer.parseHttpResponseToStream(response);
String responseFromServer = postDataToServer
.convertStreamToString(contentStream);
if (responseFromServer != null) {
Toast.makeText(QuestionInterfaceActivity.this, "Kayıt Edildi",
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
Toast.makeText(QuestionInterfaceActivity.this, "Çıktı Hacı",
Toast.LENGTH_SHORT).show();
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putBoolean("MyBoolean", true);
savedInstanceState.putDouble("myDouble", 1.9);
savedInstanceState.putInt("MyInt", 1);
savedInstanceState.putString("MyString", "Welcome back to Android");
// etc.
super.onSaveInstanceState(savedInstanceState);
finish();
}
public void onDestroy() {
super.onDestroy();
android.os.Process.killProcess(android.os.Process.myPid());
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
Toast.makeText(QuestionInterfaceActivity.this, "Hoşgeldin Hacı",
Toast.LENGTH_SHORT).show();
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
double myDouble = savedInstanceState.getDouble("myDouble");
int myInt = savedInstanceState.getInt("MyInt");
String myString = savedInstanceState.getString("MyString");
}
#Override
protected void onResume() {
super.onResume();
}
public void onshowAnswer(View v) {
callEvaluationActivity(1, "A");
}
public void onshowQuestion(View view) {
setContentView(R.layout.buttontry);
loadDesign();
showQuestion();
}
public void goHome(View view) {
beforeQuitProcess();
Intent intent = new Intent(QuestionInterfaceActivity.this,
LoginEvaluation.class);
intent.putExtra("userId", userId);
startActivity(intent);
}
public void createButton(final String text) {
Button button = new Button(this);
button.setTextColor(Color.parseColor("#000000"));
button.setBackgroundResource(R.drawable.button_selector);
button.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
clickMeMyFriend(view, text);
}
});
button.setText(text);
if (text.equals("A")) {
layoutForA.addView(button);
}
if (text.equals("B")) {
layoutForB.addView(button);
}
if (text.equals("C")) {
layoutForC.addView(button);
}
if (text.equals("D")) {
layoutForD.addView(button);
}
if (text.equals("E")) {
layoutForE.addView(button);
}
}
private void clickMeMyFriend(View view, String chooice) {
if (chooice.equals("A")) {
approveAnswer(2, "A");
}
if (chooice.equals("B")) {
approveAnswer(2, "B");
}
if (chooice.equals("C")) {
approveAnswer(2, "C");
}
if (chooice.equals("D")) {
approveAnswer(2, "D");
}
if (chooice.equals("E")) {
approveAnswer(2, "E");
}
}
public void onTotalAClick(View view) {
switch (view.getId()) {
case R.id.choiceTotalPlain:
choiceATotalPlain.setBackgroundResource(R.drawable.black_button);
approveAnswer(2, "A");
break;
case R.id.choiceBTotalPlain:
choiceBTotalPlain.setBackgroundResource(R.drawable.black_button);
approveAnswer(2, "B");
break;
case R.id.choiceCTotalPlain:
approveAnswer(2, "C");
choiceCTotalPlain.setBackgroundResource(R.drawable.black_button);
break;
case R.id.choiceDTotalPlain:
approveAnswer(2, "D");
choiceDTotalPlain.setBackgroundResource(R.drawable.black_button);
break;
case R.id.choiceETotalPlain:
approveAnswer(2, "E");
choiceETotalPlain.setBackgroundResource(R.drawable.black_button);
break;
default:
break;
}
}
}
Thanks for all help
Thanks too much for your effort Barak , Alex Lockwood and the others too i recode my xml layout upon your advices nothing changed but i could seen an error cant be realize before due to my unnecassary LinearLayout block .Whatever the error is :there is a statement in my layout
android:textStyle="#style/boldText"
in this statement the value can be only bold or normal etc .this statement should be like
style="#style/choiceStyle"
thanks for your help .I decided not to work after 00:00
Are you saying you are trying to use setContentView more than once in an activity?
From everything I have read, that won't work.
If you want to change your UI without switching activities you need to use fragments, or put all of the Views you want into your one layout and hide/show only the relevant ones for each portion of your activity with setVisibility().
The reason why you are getting a NumberFormatException is because #2131230721 is not an integer. Here's what you should do:
Re-do your entire XML layout. I am not kidding... the layout you have posted is an absolute disaster. Sorry if that's mean, but I can't let you go on thinking this is the correct way to make your layouts :).
From what I can tell, you are wrapping every single view in a LinearLayout to achieve some sort of margin/padding effect. This is what the android:margin and android:padding attributes are for. Don't over-complicate things with weird android:layout_weight values, as this will make your app run slower when your layout gets inflated. If you ever find that your XML has more than 3 or 4 LinearLayouts you should take a step back and see if you are missing an easier, more efficient solution. It is frowned upon to have nested LinearLayouts too, as it is expensive to inflate these at runtime and will drain your battery as a result.
Do a Project --> Clean and restart eclipse.
Post more information. For example, your entire logcat output would be nice (not just one line). Posting your code is almost always a good idea too. It is very difficult to understand the problem from the tiny amount of information you have provided. Remember that it is beneficial to you to provide as much information as you can because the more information we have, the more likely it is that we can help answer your question. You should also provide us with line numbers and/or indicate on which lines the errors occur.
Oh yeah, and welcome to StackOverflow... :P
Is it possible that the weights are causing the problems? I've never used weights as decimals before, I thought they had to be real numbers, I mean like 1 or 2 etc. Floor numbers. Just a thought
From what I can see its something to do with a number and a text view, this could either be the text views color, weight, ID or style.
What's in style/boldText and style/rightAnswer?
You layout file does Start with a LinearLayout and defines a xmlns:android="http://schemas.android.com/apk/res/android", but you end up with a closing <ScrollView> Tag? Is there anything missing? Plus, javaCode would be great!
By the way: did u try to "clean" you project in eclipse, using Project->Clean?
This resets the R file and often helps!

Android 4 SDK text.getText() error in Eclipse

I been thinking about developing for Android for some time now, and I finally took the plunge.
Eclipse is set up, Android SDK, and ADT Plugin for eclipse is also.
I found a tutorial on line and was following it's instructions.
My problem that I can not figure out is that Eclipse generates and error with the following code, primarily the text.setText() and text.getText() calls, it underlines the text portion of it:
Am I missing an import?
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
public class testActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
// This method is called at button click because we assigned the name to the
// "On Click property" of the button
public void myClickHandler(View view) {
switch (view.getId()) {
case R.id.button1:
RadioButton celsiusButton = (RadioButton) findViewById(R.id.radioButton1);
RadioButton fahrenheitButton = (RadioButton) findViewById(R.id.radioButton2);
if (text.getText().length() == 0) {
Toast.makeText(this, "Please enter a valid number",
Toast.LENGTH_LONG).show();
return;
}
float inputValue = Float.parseFloat(text.getText().toString());
if (celsiusButton.isChecked()) {
text.setText(String
.valueOf(convertFahrenheitToCelsius(inputValue)));
celsiusButton.setChecked(false);
fahrenheitButton.setChecked(true);
} else {
text.setText(String
.valueOf(convertCelsiusToFahrenheit(inputValue)));
fahrenheitButton.setChecked(false);
celsiusButton.setChecked(true);
}
break;
}
}
// Converts to celsius
private float convertFahrenheitToCelsius(float fahrenheit) {
return ((fahrenheit - 32) * 5 / 9);
}
// Converts to fahrenheit
private float convertCelsiusToFahrenheit(float celsius) {
return ((celsius * 9) / 5) + 32;
}
}
Instead of your code use this,
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
public class ConvertActivity extends Activity {
private EditText text;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (EditText) findViewById(R.id.editText1);
}
// This method is called at button click because we assigned the name to the
// "On Click property" of the button
public void myClickHandler(View view) {
switch (view.getId()) {
case R.id.button1:
RadioButton celsiusButton = (RadioButton) findViewById(R.id.radio0);
RadioButton fahrenheitButton = (RadioButton) findViewById(R.id.radio1);
if (text.getText().length() == 0) {
Toast.makeText(this, "Please enter a valid number",
Toast.LENGTH_LONG).show();
return;
}
float inputValue = Float.parseFloat(text.getText().toString());
if (celsiusButton.isChecked()) {
text.setText(String
.valueOf(convertFahrenheitToCelsius(inputValue)));
celsiusButton.setChecked(false);
fahrenheitButton.setChecked(true);
} else {
text.setText(String
.valueOf(convertCelsiusToFahrenheit(inputValue)));
fahrenheitButton.setChecked(false);
celsiusButton.setChecked(true);
}
break;
}
}
// Converts to celsius
private float convertFahrenheitToCelsius(float fahrenheit) {
return ((fahrenheit - 32) * 5 / 9);
}
// Converts to fahrenheit
private float convertCelsiusToFahrenheit(float celsius) {
return ((celsius * 9) / 5) + 32;
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/myColor"
android:orientation="vertical" >
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal|numberSigned" >
</EditText>
<RadioGroup
android:id="#+id/radioGroup1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="#string/celsius" >
</RadioButton>
<RadioButton
android:id="#+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/fahrenheit" >
</RadioButton>
</RadioGroup>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="myClickHandler"
android:text="#string/calc" >
</Button>
</LinearLayout>
You didn't declare the textedit object.
In your onCreate method add:
text = (EditText) findViewById(R.id.editText1);
editText1 maybe different, depending on ur main.xml layout file
Also add, before the onCreate method this:
private EditText text;
Seems like you have not declared text, what is it a TextView or an EditText?
Define it like this
public class testActivity extends Activity {
/** Called when the activity is first created. */
TextView text;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (TextView)findViewById(R.id.yourTextViewId);
}
After declaring it this way you wouldn't see the error.

Categories

Resources