How to add different values in same TextView in Android - java

A want to develop a project in android using SOAP service protocol. So that i get XML and parse it into String array. I want to show one String (Like String[0]) in one TextView then when a user click the next button next String (Like String[1]) will show on the same page and the same TextView. How how could i do that?

Probably you do not know much of android.
in your main activity class where you want to show data create the filed String array as
public class NNN extends Activity {
//... some other fields
private String[] data;
private int current;
Private TextView yourTextView;
//in on create
data = null;
current = 0;
yourTextView = (TextView) findViewById(R.id.myTextView);
then in the method where you parsed the XML of string array do
data = parsedArray;
current =0;
then on button click where you want to set the text to text view
if(data ! = null) {
//means you have parsed XML to string array
if(current != data.length) {
//means there is some data that user did not viewd
youTextView.setText(data[current]);
current++;
}
}
You must see some tutorials to get familiar to the android. See Creating hello world app

I don't know the SOAP architecture. But I will assume you store the strings parsed as following array. And also we must keep track of the current displaying string:
static String[] myparsedarray;
static int curIndex;
add an OnClickListener to your 'next' button:
class MyActivity extends Activity {
//your string array
static String[] myparsedarray;
static int curIndex;
.
.
. //lots of other code
// inside onCreate()
public void onCreate(...) {
Button nextBut = (Button) findViewById(R.id.nextbutton);
nextBut.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
TextView myloopingtext = (TextView) findViewById(R.id.mytextview);
curIndex = (curIndex + 1) % myparsedarray.length;
//the modulus to avoid arrayIndexOutOfBoundsException :)
myloopingtext.setText(myparsedarray[curIndex]);
}
});
.
.
. //rest of the code
}
}
P.S others: Correct me if I am wrong :)
edit: As indivisible said, look into android tutorials. I also suggest you search for similar questions. Cheers!

Related

How to dynamically keep on adding items from an EditText field?

I am trying to add the text written in a textfield everytime and add it into an ArrayList. For eg- if the text "abcdef" is written in the textfield, then it should get added into the list. Again if the text "ghijkl" is written in the textfield, than that should get added.
My code for adding the text into the listview:
final ArrayList<String> mylist = new ArrayList<String>(5);
String s3=text1.getText().toString();
if(s3!=null)
g++;
else g--;
if(g>0) {
for(int i=0;i<mylist.size();i++) {
mylist.add(s3);
Toast.makeText(getApplicationContext(), mylist.get(i), Toast.LENGTH_LONG).show();
}
}
Is this the right way to do this? Also I am trying to get the list item for testing purpose, but I don't get any toast.
I assume you like to add the Content of your EditText field into the list after pressing a button, so you could do it like this:
// Member to store your Texts in list
private ArrayList<String> _list = new ArrayList<>()
// Method to call to add an entry to your list
// Either by pressing a button, removing focus of your edit text or something else
private void addTextToList()
{
String text = text1.getText().toString();
if (text != null)
{
_list.add(text);
}
}
private void showToast()
{
for(String text: _list)
{
Toast.makeText(this, mylist.get(i), Toast.LENGTH_LONG).show();
}
}
The toast is not shown because you need to pass your current activity.
Assuming your Code is in your activity, I passed this in the example above.
you have to make a button to handle this action every click i make editTex ,textView and Button
this is the action of button it every click take the value of editText and stor it in ArrayList and increse String by this value
public void getText(View v){
if(ed.getText().toString().length()!=0){
s+="\n"+ed.getText().toString();
arr.add(ed.getText().toString());
}
tv.setText(s);
}

Convert string array to int array android

I'm trying to convert an string array (listview_array) to int array, and then compare numbers. Unfortunately, the app is crashing everytime I execute it.
Here is the code:
public class FindStop3 extends Activity implements OnItemClickListener{
private String stop,line,listview_array[],buschain,dayweek,weekly;
private int selected,day;
private TextView tvLine,tvToday,tvNext;
private ListView lv;
String currentdate = java.text.DateFormat.getDateInstance().format(Calendar.getInstance().getTime());//Get current time
String currenttime = java.text.DateFormat.getTimeInstance().format(Calendar.getInstance().getTime());//Get current time
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_stop3);
FindStop3.this.overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);//Lateral transition
Intent intent = getIntent();//Take data from last activity
Bundle bundle = intent.getExtras();
line=bundle.getString("Line");//Takes the previous selected line from the last activity
stop=bundle.getString("Stop");//Takes the previous selected stop from the last activity
setTitle("Selected stop: "+stop);//Modifies title
getDayOfWeek();//Gets day of week
getBusChain(line,stop,weekly);//Calls method to get the xml chain name
tvLine = (TextView) findViewById(R.id.tvLine);
tvLine.setText("Line from "+line);
tvNext = (TextView) findViewById(R.id.tvNext);
tvNext.setText("Next bus arrives at "+currenttime);
tvToday = (TextView) findViewById(R.id.tvToday);
tvToday.setText(dayweek+","+currentdate+" schedule:");
selected= getResources().getIdentifier(buschain, "array",
this.getPackageName());//Lets me use a variable as stringArray
listview_array = getResources().getStringArray(selected);
lv = (ListView) findViewById(R.id.lvSchedule);
lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, listview_array));
getNextBus();
}
And here is the method to convert it:
public void getNextBus () {
//Converts listview_array into an integer array
int myar[]=new int[listview_array.length];
for(int i=0;i<listview_array.length;i++){
myar[i]=Integer.parseInt(listview_array[i]);
}
If the method is not executed, the application works perfectly. The values are taken from an xml file as follows:
<string-array name="Schedule">
<item>05:40</item>
<item>06:00</item>
<item>06:16</item>
<item>06:28</item>
<item>06:40</item>
<item>07:16</item>
<item>07:29</item>
<item>07:43</item>
<item>07:55</item>
<item>08:07</item>
<item>08:22</item>
</string-array>
Could anyone gives an idea about what can be the problem?
Thanks.
I think that your problem is when you try to convert the values, because a value like this "05:40" cannot be converted into a int.
Problably, you're getting a NumberFormatException.
If you want a better answer please send the log of your app.

Android EditText Content is Empty, Even When Text is Shown

I have an EditText field that represents an ID number. That field can either be filled programmatically, using IDField.setText(String) based on the results of a card swipe, or it can be filled manually using the keyboard.
Once the text is filled both methods (auto login--based on swipe, or manual--based on button click) both run the same sign in script. However when I go to grab the contents of the EditText field, if I edited the text manually I get an empty string returned. If the text was set programmatically then it works perfectly.
This doesn't make any sense to me. Is there a reason that editText.getText().toString() would not return the content that is visibly shown in the textbox?
XML:
<Button
android:id="#+id/btn_swipeCard"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/signInID"
android:layout_toLeftOf="#+id/textView1"
android:onClick="SignInStudent"
android:text="Swipe ID" />
Button Initialization:
IDField = (EditText) layout.findViewById (R.id.signInID);
LoginButton = (Button) findViewById(R.id.button1);
LoginButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { SignInStudent(); } } );
Card Swipe:
// displays data from card swiping
private Runnable doUpdateTVS = new Runnable()
{
public void run()
{
try
{
//Grab ID Number
String[] splitMSG = strMsrData.split("=");
//txtIDNumber.setText(splitMSG[2]);
IDField.setText(splitMSG[2]);
StringBuffer hexString = new StringBuffer();
hexString.append("<");
String fix = null;
for (int i = 0; i < msrData.length; i++) {
fix = Integer.toHexString(0xFF & msrData[i]);
if(fix.length()==1)
fix = "0"+fix;
hexString.append(fix);
if((i+1)%4==0&&i!=(msrData.length-1))
hexString.append(' ');
}
hexString.append(">");
myUniMagReader.WriteLogIntoFile(hexString.toString());
SignInStudent();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
};
Sign In Logic:
public void SignInStudent()
{
String temp = "http://wwww.tempUrl.com/signIn?ID="+ IDField.getText().toString() + "&DeviceId="+KEY;
webView.loadUrl(temp);
}
The layout is only updated during the onCreate phase of the loop. This is fired when an onResume event is called as well which explains why the fields update after you lock and unlock the device. There are a few workarounds for this such as doing more background processing and then creating a new view with correct values, or using a surfaceView that allows drawing to occur while the program is in its normal execute cycle.
For my application I either do background processing and then move to a new view, or have a view that just keeps calling itself to get the onCreate events to fire again. The solution depends on the application, but that's why the problem occurs.

android - SimpleCursorAdapter for a View

is it possible to create a View which is driven by a SimpleCursorAdapter. The content from this view is ever time a entry from DB.
The View (dataView) looks like:
txtData1
txtData2
txtData3
btnPrev btnNext
I read around and tryd to setup this behavior. Hope its make sens:
public class mActivity extends Activity {
public Context me = this;
public SimpleCursorAdapter mAdapter = null;
public Cursor mCursor = null;
private OnClickListener btnStart_onClick = new OnClickListener() {
public void onClick(View v) {
setContentView(R.layout.dataView);
mCursor = mDB.rawQuery("SELECT * FROM Data", null);
startManagingCursor(mCursor);
mAdapter = new SimpleCursorAdapter(
me,
R.layout.dataView,
mCursor,
new String[] {"Data1", "Data2", "Data3"},
new int[] {R.id.txtData1 , R.id.txtData2, R.id.txtData3});
mAdapter.setViewBinder(VIEW_BINDER);
mCursor.moveToFirst();
}
};
static final ViewBinder VIEW_BINDER = new ViewBinder() {
public boolean setViewValue(View view, Cursor cursor, int columnIndex)
{
switch (view.getId())
{
case R.id.txtData1:
TextView txt = (TextView) view;
if (txt != null)
{
int index = cursor.getColumnIndex("Data1");
txt.setText(cursor.getString(index));
}
return true;
case R.id.txtData2:
TextView txt = (TextView) view;
if (txt != null)
{
int index = cursor.getColumnIndex("Data2");
txt.setText(cursor.getString(index));
}
return true;
case R.id.txtData3:
TextView txt = (TextView) view;
if (txt != null)
{
int index = cursor.getColumnIndex("Data3");
txt.setText(cursor.getString(index));
}
return true;
default:
return false;
}
}
};
}
When I run from the btnStart_onClick I dont get Data in my Textboxes :-(
Can somebody help? Can it work like this?
Next question: how can I use the Prev or Next Buttons? Possible this is the only thing I miss to "load" the first data...
EDIT: I extended my example with the global mCursor and the call to mCursor.moveToFirst()
On my app I also tested with the next / prev buttons and the function mCursor.moveToNext() and mCursor.moveToPrevious()
But its not change :-(
As far as I can tell, there are a lot of what I think are conceptual/organizational/syntactical problems with your code. First of all, an adapter is usually exploited by a view such as ListView or Spinner, that gets populated with the data retrieved by the adapter via the cursor (or whatever data structure is backing it). However, I don't see this pattern in your code, and I'm left wondering what use an adapter would have in your case.
Second, you perform a whole SELECT * query in your click listener, i.e. you retrieve all your 1000 records for each click on... well, on what, exactly? You define the click listener, but never set it onto anything - just as you define the adapter, but you don't bind it to anything. The code that sets up the adapter, with the database query and the binder should really be placed outside the listener.
Last, I believe you mocked variable names a bit before posting the code, because in the following snippet:
TextView txt = (TextView) view;
if (txt != null)
{
int index = cursor.getColumnIndex("Data1");
String txt = cursor.getString(index);
txt.setText(txt);
}
I could hardly see how the compiler is intended to distinguish the two txt variables on the last line of the if body.

Can't update TextView from another activity

I have an activity with a TextView that needs to be updated from a second activity.
I can pass the Text view data to the 2nd activity ok, but when I try to update that TextView
within the 2nd activity it crashes. My code:
1st Activity (where the TextView is defined in my xml):
Intent intent = new Intent(1stactivity.this, 2ndactivity.class);
intent.putExtra("homescore_value", ((TextView)findViewById(R.id.score_home)).getText());
startActivity(intent);
// code snippet
Then in my 2nd activity:
Bundle bundle = getIntent().getExtras();
hometext = bundle.getString("homescore_value"); // this works and displays the correct String from 1st activity,
but it crashes when I try to pull in as a TextView:
// other code snipped
int homescore = 0;
String Home_nickname = "HOME ";
TextView homestext = (TextView) bundle.get("homescore_value");
hometext.setText(Home_nickname +": "+homescore );
Please help.
You are trying to get a String as a TextView (you are setting a String in the intent from the first Activity).
You trying to cast String to TextView. The code that crashes is equivalent of:
String text = bundle.get("homescore_value"); //this is ok
TextView textView = (TextView)text; //this is bad
You should do instead:
String text = bundle.get("homescore_value");
TextView textView = (TextView)findViewById(R.id.yourTextViewId);
textView.setText(text);
This line here:
intent.putExtra("homescore_value", ((TextView)findViewById(R.id.score_home)).getText());
is attaching a String along with the intent, not a TextView.
You must inflate a new TextView within the 2nd activity, by either declaring it in the layout.xml, or programmatically placing it within the layout.
Something that solved part of this problem for me was setting the receiving String variables to null like this:
public String param1new = null;
public String param2new= null;
My issue with this is I'm trying to set background colors on several TextViews and only the first one is being set at this time.

Categories

Resources