I created one mini App for learning,
When any user give any number in EditText and click on submit, then TextView & EditText created dynamically based on given Digit.
and After created new EditText, user fill Data in EditText and click on submit button...
When user click on submit data must pass in new intent and Display that data in it.
My Problem is that when I click on submit button,
only Last EditText Value is display...
What Can I Do?
Thanks In Advance...!!!
Here is my Code...
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:hint="Enter Digit Here" >
<requestFocus />
</EditText>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ADD" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent" >
<Button
android:id="#+id/button2"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DELETE" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent" >
<Button
android:id="#+id/button3"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SUBMIT" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/LinearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
</LinearLayout>
MainAvtivity.java
package com.example.textviewdemo;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
private TextView addTv;
private EditText edt, edtAdd, edArray;
private Button add, delete, submit;
LinearLayout layout;
List<EditText> allEds;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt = (EditText) findViewById(R.id.editText1);
add = (Button) findViewById(R.id.button1);
delete = (Button) findViewById(R.id.button2);
submit = (Button) findViewById(R.id.button3);
layout = (LinearLayout) findViewById(R.id.LinearLayout);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int no = Integer.parseInt(edt.getText().toString());
allEds = new ArrayList<EditText>();
for (int i = 0; i < no; i++) {
addTv = new TextView(MainActivity.this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
layout.setLayoutParams(params);
addTv.setText("TextView " + i);
addTv.setId(i);
layout.addView(addTv);
edtAdd = new EditText(MainActivity.this);
layout.setLayoutParams(params);
allEds.add(edtAdd);
edtAdd.setText("Test" + i);
edtAdd.setId(i);
layout.addView(edtAdd);
}
}
});
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent data = new Intent(MainActivity.this, Display.class);
String[] items = new String[allEds.size()];
String str = String.valueOf(allEds.size());
for (int j = 0; j < allEds.size(); j++) {
items[j] = allEds.get(j).getText().toString();
data.putExtra("edData", items[j]);
data.putExtra("size", str);
/*
* Toast.makeText(getApplicationContext(), items[j],
* Toast.LENGTH_SHORT).show();
*/
}
startActivity(data);
}
});
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layout.removeAllViews();
}
});
}
}
Display.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/LinearLayout_1" >
</LinearLayout>
</LinearLayout>
Display.java
package com.example.textviewdemo;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;
public class Display extends ActionBarActivity {
TextView getText;
LinearLayout linear;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
Intent get = getIntent();
linear = (LinearLayout) findViewById(R.id.LinearLayout_1);
int size = Integer.parseInt((get.getExtras().getString("size")));
for (int i = 0; i < size; i++) {
getText = new TextView(Display.this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
getText.setText(get.getExtras().getString("edData"));
linear.setLayoutParams(params);
getText.setId(i);
linear.addView(getText);
}
}
}
My Problem is that when I click on submit button,
only Last EditText Value is display...
Because, you are overwriting the data in your for loop using this key:
for (int j = 0; j < allEds.size(); j++) {
items[j] = allEds.get(j).getText().toString();
data.putExtra("edData", items[j]);
data.putExtra("size", str);
}
And later, retrieve using index id till j = size.
You can either use index in key or pass String array itself:
Approach 1:
data.putExtra("size", str); //you don't need to keep this in loop as its same.
for (int j = 0; j < allEds.size(); j++) {
items[j] = allEds.get(j).getText().toString();
data.putExtra("edData"+j, items[j]);
}
and
int size = Integer.parseInt(getIntent().getStringExtra("size"));
for (int j = 0; j < size; j++) {
Intent intent = getIntent();
String str = intent.getStringExtra("edData"+j);
}
Approach 2:
Pass String array in intent, and later, retrieve it in second activity:
intent.putExtra("strings", myStringArray);
and
Intent intent = getIntent();
String[] myStrings = intent.getStringArrayExtra("strings");
Hope this helps.
Please check below you are updating the value every time that's why it is only showing last digit.
package com.example.textviewdemo;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
private TextView addTv;
private EditText edt, edtAdd, edArray;
private Button add, delete, submit;
LinearLayout layout;
List<EditText> allEds;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt = (EditText) findViewById(R.id.editText1);
add = (Button) findViewById(R.id.button1);
delete = (Button) findViewById(R.id.button2);
submit = (Button) findViewById(R.id.button3);
layout = (LinearLayout) findViewById(R.id.LinearLayout);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int no = Integer.parseInt(edt.getText().toString());
allEds = new ArrayList<EditText>();
for (int i = 0; i < no; i++) {
addTv = new TextView(MainActivity.this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
layout.setLayoutParams(params);
addTv.setText("TextView " + i);
addTv.setId(i);
layout.addView(addTv);
edtAdd = new EditText(MainActivity.this);
layout.setLayoutParams(params);
allEds.add(edtAdd);
edtAdd.setText("Test" + i);
edtAdd.setId(i);
layout.addView(edtAdd);
}
}
});
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent data = new Intent(MainActivity.this, Display.class);
String[] items = new String[allEds.size()];
String str = String.valueOf(allEds.size());
for (int j = 0; j < allEds.size(); j++) {
items[j] = allEds.get(j).getText().toString();
/*
* Toast.makeText(getApplicationContext(), items[j],
* Toast.LENGTH_SHORT).show();
*/
}
//changes made here
data.putExtra("edData", items);
data.putExtra("size", str);
startActivity(data);
}
});
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layout.removeAllViews();
}
});
}
}
package com.example.textviewdemo;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;
public class Display extends ActionBarActivity {
TextView getText;
LinearLayout linear;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
Intent get = getIntent();
linear = (LinearLayout) findViewById(R.id.LinearLayout_1);
int size = Integer.parseInt((get.getExtras().getString("size")));
for (int i = 0; i < size; i++) {
getText = new TextView(Display.this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
String[] data = get.getExtras().getString("edData");
String textOnRequest = ";
for(int i=0 ; i < data.length ; i++){
textOnResponse += data[i];
}
getText.setText(textOnResponse);
linear.setLayoutParams(params);
getText.setId(i);
linear.addView(getText);
}
}
}
You can use Shared Preferences to store values,
And later on you can retrieve from shared preferences.
Write to Shared Preferences
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
Read from Shared Preferences
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
Check in Google API Shared - Preferences
Move data.putExtra for both size and edData keys outside for loop data.putExtra work like a Map which have a unique keys
// Prepare items Array
for (int j = 0; j < allEds.size(); j++) {
items[j] = allEds.get(j).getText().toString();
}
data.putExtra("edData", items);
data.putExtra("size", str);
Now get edData as String Array instead of String from Bundle.
Related
I am trying to increase the value of variable count by one each time i click on the button to switch the activity back and forth. However, each time i clicked, the count value is still the same. Can someone kindly help ?
I am trying to put some life-cycle android code, but it still does not make any difference.
package com.darayuth.learning;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
public class MainActivity extends AppCompatActivity {
public static final String EXTRA_MESSAGE = "com.darayuth.learning";
public static final String TAG = "MainActivity";
public static final String value = "value";
private int count = 0;
private TextView textView;
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt(value, count);
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
count = savedInstanceState.getInt(value);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView2);
Button btn = findViewById(R.id.button);
btn.setOnClickListener((View v)->{
sendMessage();
});
}
public void sendMessage(){
count = count + 1;
Log.i(TAG, "value: " + count);
Intent intent = new Intent(this, Main2Activity.class);
EditText editText = findViewById(R.id.editText);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message );
startActivity(intent);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="sendMessage"
android:text="Button" />
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="Name" />
</LinearLayout>
activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Main2Activity">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
package com.darayuth.learning;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class Main2Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
TextView textView = findViewById(R.id.textView1);
textView.setText(message);
}
}
I would suggest using SharedPreferences to store and retrieve the value between your activities.
private void storeValue(){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
// Store an integer using the Shared Preferences editor
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("myPreferenceValueKey", value); // Store the value with a key to identify it
editor.apply();
}
private void retrieveValue(){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
int defaultValue = 0; // This is the value that's returned if the preference doesn't exist
// Retrieve the stored value using the associated key
value = prefs.getInt("myPreferenceValueKey", defaultValue);
}
In your first Activity, just call retrieveValue() in your onCreate() then call storeValue() after incrementing the value but before starting the next Activity.
You can create the same functions in your second Activity to store and retrieve the value as needed.
You can learn more about SharedPreferences at https://developer.android.com/training/data-storage/shared-preferences
I suggest you use a class with a static variable to hold the count variable. And add a function increment() to increase the count.
I want to add a button to one of my activities (that displays a news article), so when the user clicks the button the article is opened in their browser. So far I have added the button in my xml and it appears. I'm just having some trouble with the click listener. Below is my code, i'm getting an error for 'setOnClickListener' which is 'Non-static method 'setOnClickListener(android.view.View.onClickListener)' cannot be referenced from a static content.
I'm not sure what this means! maybe i'm not calling the method in the right place or there is just an error with the method itself?
Please could someone take a look, thanks!
import android.content.Intent;
import android.media.Image;
import android.net.Uri;
import android.support.v4.app.ShareCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.ShareActionProvider;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.view.View.OnClickListener;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.NetworkImageView;
import org.json.JSONException;
import org.json.JSONObject;
public class NewsItemActivity extends AppCompatActivity {
//Declare java object for the UI elements
private TextView itemTitle;
private TextView itemDate;
private TextView itemContent;
private NetworkImageView itemImage;
private ShareActionProvider mShareActionProvider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news_item);
itemTitle = (TextView) findViewById(R.id.itemTitle);
itemDate = (TextView) findViewById(R.id.itemDate);
itemContent = (TextView) findViewById(R.id.itemContent);
itemImage = (NetworkImageView) findViewById(R.id.itemImage);
EDANewsApp app = EDANewsApp.getInstance();
Intent intent = getIntent();
int itemId = intent.getIntExtra("newsItemId", 0);
String url = "http://www.efstratiou.info/projects/newsfeed/getItem.php?id="+itemId;
JsonObjectRequest request = new JsonObjectRequest(url, listener, errorListener);
app.requestQueue.add(request);
Button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = getIntent();
int itemId = intent.getIntExtra("newsItemId", 0);
String shareUrl = "http://www.efstratiou.info/projects/newsfeed/getItem.php?id=" + itemId;
Intent buttonIntent = new Intent();
buttonIntent.setAction(Intent.ACTION_VIEW);
buttonIntent.addCategory(Intent.CATEGORY_BROWSABLE);
buttonIntent.setData(Uri.parse(shareUrl));
startActivity(buttonIntent);
}
});
};
activity_news_item.xml
<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"
tools:context=".NewsItemActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/itemTitle"
android:layout_margin="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#3183b9"/>
<TextView
android:id="#+id/itemDate"
android:layout_marginLeft="15dp"
android:layout_marginBottom="15dp"
android:textSize="16sp"
android:textStyle="italic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/itemImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/itemContent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20sp"
android:textSize="16sp"
/>
<Button
android:id="#+id/BrowserButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="View in browser"
android:layout_marginLeft="15dp"
style="#style/BrowserButton"
/>
</LinearLayout>
</ScrollView>
</RelativeLayout>
Change
Button.setOnClickListener(new View.OnClickListener() { ... });
to
Button button = (Button) findViewById(R.id.BrowserButton);
button.setOnClickListener(new View.OnClickListener() { ... });
You need to call the setOnClickListener method on an instance of Button, not on the class itself.
The problem is this :
Button.setOnClickListener(new View.OnClickListener() {
You have to declare it out of onCreate() as you did with your Textviews as :
Button btn;
Why?
Because if you put it on onCreate() you wont be able to use this object out of onCreate() so it's recomendable to put it as a public object.
Then in your onCreate() do this :
btn = (Button)findViewById(R.id.BrowserButton);
Then you do the OnclickListener() as follows :
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = getIntent();
int itemId = intent.getIntExtra("newsItemId", 0);
String shareUrl = "http://www.efstratiou.info/projects/newsfeed/getItem.php?id=" + itemId;
Intent buttonIntent = new Intent();
buttonIntent.setAction(Intent.ACTION_VIEW);
buttonIntent.addCategory(Intent.CATEGORY_BROWSABLE);
buttonIntent.setData(Uri.parse(shareUrl));
startActivity(buttonIntent);
}
});
I'm still getting an error for onClickListener, saying it 'cannot resolve symbol'.
Make sure that you've imported this :
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
You can do it doing this :
Add implements OnClickListener { as follows :
public class NewsItemActivity extends AppCompatActivity implements View.OnClickListener {
Then on your Button you do this :
btn = (Button)findViewById(R.id.BrowserButton);
btn.setOnClickListener(this);
Then add a switch case as follows :
public void onClick(View v) {
switch(v.getId()) {
case R.id.BrowserButton:
Intent intent = getIntent();
int itemId = intent.getIntExtra("newsItemId", 0);
String shareUrl = "http://www.efstratiou.info/projects/newsfeed/getItem.php?id=" + itemId;
Intent buttonIntent = new Intent();
buttonIntent.setAction(Intent.ACTION_VIEW);
buttonIntent.addCategory(Intent.CATEGORY_BROWSABLE);
buttonIntent.setData(Uri.parse(shareUrl));
startActivity(buttonIntent);
}
break;
}
}
I'm trying to launch an activity using intents and setting values in TextViews in the launched activity, but when I try to do that my app crashes. Heres the activity I'm trying to launch. It crashes when i try to set the text in the last two code lines
public class GameOver extends Activity {
TextView correctTxt;
TextView incorrectTxt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
int correct = intent.getIntExtra("correct", 0);
int incorrect = intent.getIntExtra("incorrect", 0);
correctTxt = (TextView)findViewById(R.id.correct_txt);
incorrectTxt = (TextView)findViewById(R.id.incorrect_txt);
correctTxt.setText("" + correct);
incorrectTxt.setText("" + incorrect);
}
}
And the activity that's launching. I make use of the intent in the trueButton onClickListener method:
package com.example.beithia.geotest;
import android.app.Activity;
import java.util.*;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.content.Intent;
public class TestActivity extends Activity {
private Button trueButton;
private Button falseButton;
private TextView questionTextView;
private TextView correctNum;
private TextView incorrectNum;
private TextView avgScore;
int numOfCorrect = 0;
int numOfIncorrect = 0;
double num = 1;
private TrueFalse[] questionBank = new TrueFalse[] {
new TrueFalse(R.string.question_oceans, true),
new TrueFalse(R.string.question_mideast, false),
new TrueFalse(R.string.question_americas, true),
new TrueFalse(R.string.question_asia,true),
new TrueFalse(R.string.question_channel_islands,true),
new TrueFalse(R.string.question_china,false),
new TrueFalse(R.string.question_mexico,true),
new TrueFalse(R.string.question_turkey,false),
new TrueFalse(R.string.question_everest,false),
new TrueFalse(R.string.question_colombia,false),
new TrueFalse(R.string.question_vatican,true),
new TrueFalse(R.string.question_nile,true),
};
private int currentIndex = 0;
private void updateQuestion() {
int question = questionBank[currentIndex].getQuestion();
questionTextView.setText(question);
}
private void checkAnswer(boolean userPressedTrue) {
boolean answerIsTrue = questionBank[currentIndex].isTrueQuestion();
int msgId = 0;
if (userPressedTrue == answerIsTrue) {
msgId = R.string.correct_toast;
numOfCorrect++;
}
else {
msgId = R.string.incorrect_toast;
numOfIncorrect++;
}
Toast.makeText(this,msgId,Toast.LENGTH_SHORT).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
questionTextView = (TextView)findViewById(R.id.question_text_view);
correctNum = (TextView)findViewById(R.id.correct_num);
incorrectNum = (TextView)findViewById(R.id.incorrect_num);
avgScore = (TextView)findViewById(R.id.average_score);
trueButton = (Button) findViewById(R.id.true_button);
trueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(true);
double score = (numOfCorrect / num) * 100;
currentIndex = (currentIndex + 1) % questionBank.length;
correctNum.setText("Correct: " + numOfCorrect);
incorrectNum.setText("Incorrect: " + numOfIncorrect);
avgScore.setText("Score: " + String.format("%.2f", score) + "%");
updateQuestion();
num++;
if(num > 10) {
Intent intent = new Intent(TestActivity.this, GameOver.class);
intent.putExtra("correct", numOfCorrect);
intent.putExtra("incorrect", numOfIncorrect);
startActivity(intent);
}
}
});
falseButton = (Button) findViewById(R.id.false_button);
falseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(false);
double score = (numOfCorrect / num) * 100;
currentIndex = (currentIndex + 1) % questionBank.length;
correctNum.setText("Correct: " + numOfCorrect);
incorrectNum.setText("Incorrect: " + numOfIncorrect);
avgScore.setText("Score: " + String.format("%.2f", score) + "%");
updateQuestion();
num++;
}
});
updateQuestion();
}
}
Here's the layout for activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/correct_num"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff00ff12" />
<TextView
android:id="#+id/incorrect_num"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ffff5440" />
<TextView
android:id="#+id/average_score"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ffff8c1a" />
<TextView
android:id="#+id/question_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="24dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/true_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/true_button"/>
<Button
android:id="#+id/false_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/false_button"/>
</LinearLayout>
</LinearLayout>
And the layout for the activity_game_over.xml:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/correct_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/incorrect_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
I can get it to work if I use the setContentView(R.layout.activity_game_over);
however when I try to launch the main activity again it starts the GameOver Activity, but it should start the GeoQuiz activity instead.
In the GameOver activity you don't set any content view setContentView(), hence you textViews cannot be found, findViewById returns null, hence you get NullPointerException when invoking setText().
I can get it to work if I use the setContentView(R.layout.activity_game_over); however when I try to launch the main activity again it starts the GameOver Activity, but it should start the GeoQuiz activity instead. Please help!
The activity that runs at start up is defined in the android manifest xml file of your project.
look for
action android:name="android.intent.action.MAIN"
Hello fellow programmers!
In my app I want some XML listed below to be inflated OnClick. It needs to be put into another LinearLayout.I also want to change the text in the TextView and the id's of the EditTexts to "ListItem"+numOfItems. How can I do this?
XML to be inflated:
<LinearLayout
android:paddingLeft="15dp"
android:weightSum="100"
android:layout_width="fill_parent"
android:layout_height="80dp"
android:orientation="horizontal">
<TextView
android:layout_weight="10"
android:layout_width="10dp"
android:layout_height="80dp"
android:text="1."
android:id="#+id/tvItem1"/>
<EditText
android:layout_weight="90"
android:layout_width="100px"
android:layout_height="80dp"
android:hint="List Item 1"
android:id="#+id/etItem1"
android:paddingTop="50px"/>
</LinearLayout>
Full java class:
package com.frostbytedev.randomgenie;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.*;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Steven on 6/23/13.
*/
public class Test extends Activity implements View.OnClickListener{
java.util.List<TextView> listOfET = new ArrayList<TextView>();
LinearLayout insideScroll;
ScrollView svItems;
TextView etItem1, etItem2;
Button Add, Remove;
int numOfItems = 2, width, height;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dynamictest);
initialize();
}
private void initialize() {
Add=(Button)findViewById(R.id.bAdd);
Remove=(Button)findViewById(R.id.bRemove);
insideScroll=(LinearLayout)findViewById(R.id.insideScroll);
etItem1=(TextView)findViewById(R.id.etItem1);
etItem2=(TextView)findViewById(R.id.etItem2);
svItems=(ScrollView)findViewById(R.id.svItems);
Add.setOnClickListener(this);
Remove.setOnClickListener(this);
listOfET.add(etItem1);
listOfET.add(etItem2);
}
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.bAdd:
numOfItems += 1;
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.HORIZONTAL);
layout.setPadding(getDP(15f), 0, 0, 0);
layout.setLayoutParams(new LinearLayout.LayoutParams((getDP(80f)), LinearLayout.LayoutParams.FILL_PARENT));
TextView numberView = new TextView(this);
LinearLayout.LayoutParams tvParams = new LinearLayout.LayoutParams(getDP(80f),getDP(10f));
numberView.setLayoutParams(tvParams);
numberView.setText(numOfItems + ".");
layout.addView(numberView);
EditText optionText = new EditText(this);
LinearLayout.LayoutParams etParams = new LinearLayout.LayoutParams(getDP(80f),getDP(100f));
numberView.setLayoutParams(etParams);
numberView.setHint("List Option "+numOfItems);
layout.addView(optionText);
insideScroll.addView(layout);
break;
case R.id. bRemove:
listOfET.remove(numOfItems);
numOfItems -= 1;
break;
}
}
private int getDP(float i) {
DisplayMetrics metrics = getResources().getDisplayMetrics();
float dp = i;
float fpixels = metrics.density * dp;
int pixels = (int) (fpixels + 0.5f);
return pixels;
}
}
This is my java class
Add the id´s to your XML items.....
<LinearLayout
android:paddingLeft="15dp"
android:weightSum="100"
android:layout_width="fill_parent"
android:layout_height="80dp"
android:orientation="horizontal">
<TextView
android:id="#+id/textViewId"
android:layout_weight="10"
android:layout_width="10dp"
android:layout_height="80dp"
android:text="1."
android:id="#+id/tvItem1"/>
<EditText
android:id="#+id/editTextId"
android:layout_weight="90"
android:layout_width="100px"
android:layout_height="80dp"
android:hint="List Item 1"
android:id="#+id/etItem1"
android:paddingTop="50px"/>
</LinearLayout>
....add this code to your listView onItemClickListener....
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView <? > parent, View view,
int position, long id) {
LayoutInflater inflater = LayoutInflater.from(getBaseContext());
View theInflatedView = inflater.inflate(R.layout.your_layout, null);
//Get the textView in your xml to set the text in it
TextView textView = theInflatedView.findViewById(R.id.textViewId);
textView.setText("Text on the textView");
//Get the EditText in you xml to set the new id
EditText editText = theInflatedView.findViewById(R.id.editTextId);
editText.setId(position);
//add the view into the LinearLayout container (global variable)
insideScroll.addView(theInflatedView);
}
});
If you are clicking a button to add items to a LinearLayout then....
your activity implements OnClickListener interface....
public class MainActivity extends Activity implements OnClickListener {
setOnClickListener to your button....
button.setOnClickListener(this);
Now you receive the click on you onClick method....
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.buttonId:
LayoutInflater inflater = LayoutInflater.from(this);
View theInflatedView = inflater.inflate(R.layout.your_layout, null);
//Get the textView in your xml to set the text in it
TextView textView = theInflatedView.findViewById(R.id.textViewId);
textView.setText("Text on the textView");
//Get the EditText in you xml to set the new id
EditText editText = theInflatedView.findViewById(R.id.editTextId);
editText.setId(linearLayout.getChildCount()+1);
//add the view into the LinearLayout (global variable)
insideScroll.addView(theInflatedView);
break;
}
}
I have tried many other questions on this site today but none of them have been helpful, i seem to have identical syntax that works for other people but every time i hit send (when i want my text fields to update) my app just crashes, I have tried a bunch of different syntax for the setText() method but nothing has worked.
Thanks for any help in advance
this is my main class
package com.example.myapp;
import android.app.Activity;
import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.*;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class TestprojectsActivity extends Activity {
private int index;
private int QsClicked = 0;
private ArrayList<String> categories = new ArrayList<String>();
private ArrayList<Button> buttons = new ArrayList<Button>();
Button b1;
Button b2;
Button b3;
Button b4;
Button changer;
private int Qselected;
TextView txt;
EditText edit;
private ArrayList<String> questions = new ArrayList<String>();
private int qnum = 0;
// updates all the buttons so we can see more categories
public void updateButtons(View v){
for(int i = 0; i < 4; i++){
if(index >= categories.size()){
index = 0;
}
buttons.get(i).setText(categories.get(index));
index++;
}
}
public void Q1(View v){
setContentView(R.layout.sub);
Qselected = index;
//send(null);
}
public void Q2(View v){
setContentView(R.layout.sub);
Qselected = (index+1);
//send(null);
}
public void Q3(View v){
setContentView(R.layout.sub);
Qselected = (index+2);
//send(null);
}
public void Q4(View v){
setContentView(R.layout.sub);
Qselected = (index+3);
//send(null);
}
public void send(View v){
edit.setText("WHY ISNT THIS WORKING?");
if(qnum < questions.size()){
txt.setText("i work!");
qnum++;
}
else{
qnum = 0;
System.exit(0);
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
index = 0;
b1 = (Button) findViewById(R.id.B1);
buttons.add(b1);
b2 = (Button) findViewById(R.id.B2);
buttons.add(b2);
b3 = (Button) findViewById(R.id.B3);
buttons.add(b3);
b4 = (Button) findViewById(R.id.B4);
buttons.add(b4);
txt = (TextView) findViewById(R.id.textView1);
edit = (EditText) findViewById(R.id.editText2);
categories.add("dumb questions");
categories.add("smart questions");
questions.add("hi there, what is your name?");
questions.add("what did you have for breakfast today?");
questions.add("how old are you?");
questions.add("what color is your hair?");
updateButtons(null);
}
}
this is my main xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layoutrowtop"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/B4"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="B4"
android:onClick="Q4" />
<Button
android:id="#+id/B3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="B3"
android:onClick="Q3" />
<Button
android:id="#+id/B2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="B2"
android:onClick="Q2" />
<Button
android:id="#+id/B1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="B1"
android:onClick="Q1" />
<Button
android:id="#+id/Button05"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="More Categories"
android:onClick="updateButtons" />
</LinearLayout>
this is my sub xml (i use it so i can have another layout)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.22"
android:text="Question"
/>
<EditText
android:id="#+id/editText2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.51"
android:ems="10"
android:inputType="text" />
<Button
android:id="#+id/send"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.08"
android:text="Send"
android:onClick="send" />
</LinearLayout>
Your activity is using main.xml as its layout, and that does not have a TextView with id editText2. Just putting such a view in sub.xml doesn't create the view; the layout file needs to be inflated and set as the content view for the activity. Call findViewById after you change layouts and all should be well.
AS in when Oncreate get call main.xml was you layout xml and it has not R.id.editText2 so at that time edit would be null..........
Put this line
edit = (EditText) findViewById(R.id.editText2);
in
public void Q1(View v){
setContentView(R.layout.sub);
Qselected = index;
edit = (EditText) findViewById(R.id.editText2); <-----------------here in Q1 Q2 Q3 Q4
//send(null);
}
In the activity's onCreate method you set the content view to R.layout.main and you search for the TextView that you want to set the text. Because the TextView is not in that layout(is in the R.layout.sub and not in the R.layout.main) it will be null and you'll get a NullPointerException when you set the text, although you set the content view as the new layout that contains that TextView(you already search for it in the onCreate method so the reference is initialized with null).
The solution is to search for the TextView after you set the new content view(R.layout.sub), for example:
public void send(View v){
txt = (TextView) findViewById(R.id.textView1);
edit = (EditText) findViewById(R.id.editText2);
edit.setText("WHY ISNT THIS WORKING?");
if(qnum < questions.size()){
txt.setText("i work!");
qnum++;
}
else{
qnum = 0;
System.exit(0);
}
}
Ans the same thing goes for that Edittext.