EditText array of existing EditTexts won't be declared right - android

I am creating an app, in which I create some EditTexts dynamically with ID number.
I want to pass the information from the EditTexts, so I tried to create a EditText array with these and then use the .getText().toString() to save them in a String Array, which I want pass to the next activity.
It seems like it won't create the "editArray[]" in second code part correctly.
Thanks in advance.
Here's my code (EnterNames.java) - Creation of EditTexts -> Succesful
protected void NumberOfEditText()
{
View VertLayout = (LinearLayout) findViewById(R.id.VertLayout);
String SpinValue = getIntent().getExtras().getString("SpinValue");
int intSpinValue = Integer.valueOf(SpinValue);
editTextCount = intSpinValue;
EditText[] editTextArray = new EditText[editTextCount];
for (int i = 0; i < editTextCount; i++)
{
String Name = "Name " + (i+1);
editTextArray[i] = new EditText(this);
editTextArray[i].setId(i+1000);
editTextArray[i].setText(Name);
editTextArray[i].setTextSize(20);
editTextArray[i].setFilters( new InputFilter[] { new InputFilter.LengthFilter(15) } );
editTextArray[i].setSelectAllOnFocus(true);
editTextArray[i].setSingleLine(true);
editTextArray[i].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
((LinearLayout) VertLayout).addView(editTextArray[i]);
}
}
Second code (EnterNames.java) - Passing data to next activity -> Failure.
By testing I think the problem is the for-loops (the editArray returns null)
public void Go(View view)
{
setContentView(R.layout.activity_enter_names);
String NameArray [] = new String [editTextCount];
EditText editArray [] = new EditText [editTextCount];
Intent intent = new Intent(this, RandomGeneration.class);
for (int i = 0; i < editTextCount; i++)
{
editArray[i] = (EditText) findViewById(i+1000);
}
for (int i = 0; i < editTextCount; i++)
{
NameArray[i] = editArray[i].getText().toString();
}
Bundle extras = new Bundle();
extras.putInt("NumberofNames", editTextCount);
extras.putStringArray("NameArray", NameArray);
intent.putExtras(extras);
startActivity(intent);
}

According to Activity.findViewById() documentation, this method will search for views in your XML, not in views added in Java.
The simple way to do what you want:
class EnterNames extends Activity {
private int editTextCount;
private EditText[] editTextArray;
protected void NumberOfEditText() {
LinearLayout vertLayout = (LinearLayout) findViewById(R.id.VertLayout);
editTextCount = Integer.valueOf(getIntent().getExtras().getString("SpinValue"));
editTextArray = new EditText[editTextCount];
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
for (int i = 0; i < editTextCount; i++) {
String Name = "Name " + (i+1);
editTextArray[i] = new EditText(this);
editTextArray[i].setText(Name);
editTextArray[i].setTextSize(20);
editTextArray[i].setFilters( new InputFilter[] { new InputFilter.LengthFilter(15) } );
editTextArray[i].setSelectAllOnFocus(true);
editTextArray[i].setSingleLine(true);
editTextArray[i].setLayoutParams(params);
vertLayout.addView(editTextArray[i]);
}
}
[…]
public void Go(View view)
{
// This will delete views added to your LinearLayout, don't use it!
//setContentView(R.layout.activity_enter_names);
String nameArray[] = new String[editTextCount];
for (int i = 0; i < editTextCount; i++) {
nameArray[i] = editArray[i].getText().toString();
}
Bundle extras = new Bundle();
extras.putInt("NumberofNames", editTextCount);
extras.putStringArray("NameArray", nameArray);
Intent intent = new Intent(this, RandomGeneration.class);
intent.putExtras(extras);
startActivity(intent);
}
}

Why you are calling setContentView(R.layout.activity_enter_names); in public void Go(View view)? You overide Activities layout in which you previously has added EditText views and all your findById() returns null.
Your code should work if you remove setContentView(R.layout.activity_enter_names); from Go function.
setContentView(R.layout.activity_enter_names); should be called single time in Activities onCreate function.

Related

Pass checked multiple images from one activity to another

I have a custom listview with checkbox imageview and textview and there is a button below listview. On clicking of that button i have to pass all the checked item details to another activity and show in other listview. I am able to pass selected value but not able to pass images. Images are in drawable folder. Please help me thanks.
Here is the code:
subscribe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String data = "";
ArrayList<Item> stList = ((OurServiceAdapter) nAdapter)
.getAllData();
for (int i = 0; i < stList.size(); i++) {
Item singleStudent = stList.get(i);
if (singleStudent.isCheckbox() == true) {
name.add(singleStudent.getName().toString());
img.add(singleStudent.getImage());
data = data + "\n" + singleStudent.getName().toString();
}
}
// byte[] imgs = singleStudent.getImage();
Intent intent = new Intent(ActivityOurServices.this, ActivityServicesForm.class);
intent.putStringArrayListExtra("key", name);
//intent.putIntegerArrayListExtra("img", img);
startActivity(intent);
}
});
}
you can pass all image as Integer arrayList :
//first : for each imageView inside list you must to set tag ,for example ;
imageView0.setTag(R.drawable.image_0);
imageView1.setTag(R.drawable.image_1);
.
.
.
imageViewN.setTag(R.drawable.image_N);
now when you press button :
ArrayList<Integer> checkedImageSrcId = new ArrayLIst<Integer> ;
for (int i = 0; i < stList.size(); i++) {
Item singleStudent = stList.get(i);
if (singleStudent.isCheckbox() == true) {
name.add(singleStudent.getName().toString());
// img.add(singleStudent.getImage());
// you most to get checked imageViews Tag and i dont have an idea about how to get those
checkedImageSrcId.add( getImageViewTagAtPostion(i));
data = data + "\n" + singleStudent.getName().toString();
}
}
// byte[] imgs = singleStudent.getImage();
Intent intent = new Intent(ActivityOurServices.this, ActivityServicesForm.class);
intent.putStringArrayListExtra("key", name);
intent.putIntegerArrayListExtra("img", checkedImageSrcId);
startActivity(intent);

How to add data in array on button click?

int size = mcq.size();
String arr[] = null;
int i;
{
for (i = 0; i < size; i++) {
if (op1.isPressed()) {
arr[i] = tv1.getText().toString();
// Log.e("Array",arr[i]);
} else if (op2.isPressed()) {
arr[i] = tv2.getText().toString();
//Log.e("Array",arr[i]);
} else if (op3.isPressed()) {
arr[i] = tv3.getText().toString();
// Log.e("Array",arr[i]);
} else if (op4.isPressed()) {
arr[i] = tv4.getText().toString();
//Log.e("Array",arr[i]);
}
I am trying to store the data in an array when the button is pressed,but it always shows null.And when the for loop is over I want to display my array.
here , Arrays in Java have a size so u cannot do like this. Instead of this
use list,
ArrayList<String> arr = new ArrayList<String>();
Inorder to do using String array :
String[] arr = new String[SIZEDEFNE HERE];
For ur answer :
ArrayList<String> arr = new ArrayList<String>();
int i;
{
for (i = 0; i < size; i++) {
if (op1.isPressed()) {
arr.add(tv1.getText().toString());
} else if (op2.isPressed()) {
arr.add(tv2.getText().toString());
} else if (op3.isPressed()) {
arr.add(tv3.getText().toString());
} else if (op4.isPressed()) {
arr.add(tv4.getText().toString());
}
Retrive value using
String s = arr.get(0);
This is because your string array is null. Declare it with the size as
String[] arr = new String[size];
Try Array List. use the following code in your main java
final ArrayList<String> list = new ArrayList<String>();
Button button= (Button) findViewById(R.id.buttonId);
final EditText editText = (EditText) findViewById(R.id.editTextId)
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
list.add(editText.getText().toString());
}
});
To avoid duplication in arraylist .You can use arraylist for faster then String array
ArrayList<String> list = new ArrayList<String>();
list.add("Krishna");
list.add("Krishna");
list.add("Kishan");
list.add("Krishn");
list.add("Aryan");
list.add("Harm");
System.out.println("List"+list);
HashSet hs = new HashSet();
hs.addAll(list);
list.clear();
list.addAll(hs);

How to store dynamically generating Textviews values in Shared preferences Android

I am querying the android Contact class and able to fetch contact name plus number and able to add multiple textviews in linear layout with number and name of the contact and able to save single textview number value in shared preferences and retrive it, how can I save dynamically adding textviews array of values (phone numbers (strings) in shared preferences. If any one provide sample code it will help me a lot, as I am doing this for the first time, by the way i searched a lot about this topic but no luck.
Here is my code:
public class Cont extends Fragment {
protected static final int PICK_CONTACT = 0;
Button showConts;
TextView[] resultTextView;
ViewGroup addItems;
final int N = 1;
String name;
String cNumber;
String[] array;
String nameContact;
String number;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View contViews = inflater.inflate(R.layout.cont, container, false);
addItems = (LinearLayout) contViews.findViewById(R.id.adds);
showConts = (Button) contViews.findViewById(R.id.opens);
resultTextView = new TextView[N]; //create an empty array;
// create a new textview
for (int i = 0; i < N; i++) {
final TextView rowTextView = new TextView(getActivity());
resultTextView = new TextView[N]; // create an empty array;
addItems.addView(rowTextView);
resultTextView[i] = rowTextView;
if(resultTextView[i] != null ){
resultTextView[i].setText(nameContact+ " "+ cNumber);
}
}
showConts.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
});
return contViews;
}
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data){
super.onActivityResult(reqCode, resultCode, data);
switch(reqCode)
{
case (PICK_CONTACT):
if (resultCode == Activity.RESULT_OK)
{
Uri contactData = data.getData();
Cursor c = getActivity().managedQuery(contactData, null, null, null, null);
if (c.moveToFirst())
{
String id = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
String hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (hasPhone.equalsIgnoreCase("1"))
{
Cursor phones = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ id,null, null);
phones.moveToFirst();
cNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//Toast.makeText(getActivity(), cNumber, Toast.LENGTH_SHORT).show();
nameContact = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
for (int i = 0; i < N; i++) {
final TextView rowTextView = new TextView(getActivity());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
params.setMargins(0,0,0,10);
resultTextView = new TextView[N];
rowTextView.setTextSize(34);
rowTextView.setHeight(140);
rowTextView.setGravity(Gravity.CENTER);
rowTextView.setBackgroundColor(Color.parseColor("#7d3f98"));
rowTextView.setTextColor(Color.WHITE);
//rowTextView.setBackgroundResource(R.drawable.corn);
addItems.addView(rowTextView);
resultTextView[i] = rowTextView;
resultTextView[i].setLayoutParams(params);
if(resultTextView[i] != null ){
resultTextView[i].setText(nameContact+ " "+ cNumber);
}
resultTextView[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String res1 = rowTextView.getText().toString();
System.out.println("num " + res1.length());
res1 = res1.split(" ")[res1.split(" ").length - 1];
startDialActivity(res1);
}
private void startDialActivity(String result) {
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:"+result));
startActivity(intent);
}
});
}
}
}
}}}}
Try google PreferenceActivity, you don't have to,you can just use the traditional way(SharedPreference sp =new ....)
, but I think SharedPreferenceActivity is very easier, it's native,very simple and powerfull!
You can make a JSONArray and add name and phone number by making JSONObject and add these JSONObjects to the JSONArray.
JSONObject mainObject=null;
try{
mainObject=new JSONObject();
JSONArray arr = new JSONArray();
for (int i = 0; i < 10; i++) {
JSONObject objName = new JSONObject();
JSONObject objPhone = new JSONObject();
objName.put("name", new String("abbcc"));
objPhone.put("phone", new String("dfdfgdf"));
arr.put(i,objName);
arr.put(i,objPhone);
}
mainObject.put("mainObj",arr);
System.out.println(mainObject.toString());
}
catch(Exception e){
}
shared.edit().putString("details",mainObject.toString()).commit();
and then get string from sharedPreferences wherever you want and the get details from JSONObject and JSONArray

java.lang.NumberFormatException: unable to parse '' as integer

i want to set the calculation result in TextView named total[] from the value of EditText named point[] .but i am able to parse the value and put it in the TextView . it give me an error in logcat
06-27 02:27:01.467: E/AndroidRuntime(275): Caused by: java.lang.NumberFormatException: unable to parse '' as integer
this is an error in logcat. i want to add integer values to the textview continuously from the edittext on the same layout
public class player_name extends Activity {
LinearLayout player_name;
TableLayout ply_name;
Bundle b,b1;
List<TextView> allEds = new ArrayList<TextView>();
List<Button> allplus = new ArrayList<Button>();
List<Button> allminus = new ArrayList<Button>();
List<EditText> alledit = new ArrayList<EditText>();
List<TextView> alltotal = new ArrayList<TextView>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_name);
b1 = getIntent().getExtras();
String[] result = b1.getStringArray("playerName");
player_name = (LinearLayout) findViewById(R.id.player_name);
ply_name = new TableLayout(this);
player_name.addView(ply_name);
TableLayout.LayoutParams tableRowParams=new TableLayout.LayoutParams
(TableLayout.LayoutParams.MATCH_PARENT,TableLayout.LayoutParams.MATCH_PARENT,1.0f);
TextView[] ed1 = new TextView[result.length+1];
Button[] plus = new Button[result.length+1];
Button[] minus = new Button[result.length+1];
EditText[] point = new EditText[result.length+1];
TextView[] total = new TextView[result.length+1];
TableRow[] TR= new TableRow[result.length+1];
int[] totalscore = null;
String[] temp = null;
Button btnResult = new Button(player_name.this);
btnResult.setText(" click here to get RESULT");
for(int i=0;i<=(result.length-1);i++) {
ed1[i] = new TextView(player_name.this);
plus[i] = new Button(player_name.this);
minus[i] = new Button(player_name.this);
point[i] = new EditText(player_name.this);
total[i] = new TextView(player_name.this);
TR[i] = new TableRow(player_name.this);
allEds.add(ed1[i]);
alltotal.add(total[i]);
alledit.add(point[i]);
allplus.add(plus[i]);
allminus.add(minus[i]);
TR[i].addView(ed1[i]);
TR[i].addView(point[i]);
TR[i].addView(plus[i]);
TR[i].addView(minus[i]);
TR[i].addView(total[i]);
ply_name.addView(TR[i]);
TR[i].setLayoutParams(tableRowParams);
totalscore[i] =Integer.parseInt(point[i].getText().toString());
temp[i] = "" + totalscore[i];
ed1[i].setId(i);
ed1[i].setHeight(50);
ed1[i].setWidth(70);
ed1[i].setText(result[i]);
ed1[i].setTextColor(Color.CYAN);
total[i].setId(i);
total[i].setHeight(50);
total[i].setWidth(70);
total[i].setText(""+0);
total[i].setTextColor(Color.CYAN);
point[i].setId(i);
point[i].setHeight(50);
point[i].setWidth(120);
point[i].setHint(result[i]+"\'s");
point[i].setInputType(InputType.TYPE_CLASS_NUMBER);
point[i].setTextColor(Color.BLACK);
plus[i].setId(i);
plus[i].setHeight(50);
plus[i].setWidth(50);
plus[i].setText("+");
plus[i].setTextColor(Color.BLACK);
minus[i].setId(i);
minus[i].setHeight(50);
minus[i].setWidth(50);
minus[i].setText("-");
minus[i].setTextColor(Color.BLACK);
plus[i].setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
minus[i].setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
}
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
player_name.addView(btnResult, lp);
btnResult.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent1 = new Intent(player_name.this,result.class);
startActivity(intent1);
}
});
}
}
You need to check whether the string you are parsing is an integer. Try this code:
if (IsInteger(point[i].getText().toString()))
totalscore[i] =Integer.parseInt(point[i].getText().toString());
and add this function:
public static boolean IsInteger(String s)
{
if (s == null || s.length() == 0) return false;
for(int i = 0; i < s.length(); i++)
{
if (Character.digit(s.charAt(i), 10) < 0)
return false;
}
return true;
}
I hope this helps

How to sort numbers in TextViews and display them?

Hi can some one suggest me a sample example of how i can sort the textviews based on the numbers in textviews. I am able to get the text from the TextViews need to sort and place the lowest number first.
Thank you.
public void sortNumbers(View v) {
String[] numbers = new String[7];
numbers[0] = textView23.getText().toString();
numbers[1] = textView33.getText().toString();
numbers[2] = textView43.getText().toString();
numbers[3] = textView53.getText().toString();
numbers[4] = textView63.getText().toString();
numbers[5] = textView73.getText().toString();
numbers[6] = textView83.getText().toString();
Integer[] intValues = new Integer[numbers.length];
for (int i = 0; i < numbers.length; i++) {
intValues[i] = Integer.parseInt(numbers[i].trim());
}
Collections.sort(Arrays.asList(intValues));
for (int i = 0; i < intValues.length; i++) {
Integer intValue = intValues[i];
//here I want to assign sorted numberes to the TextViews
}
}
So I have followed Jeffrey's advice. Here is the code which still doesn't work properly. What could be wrong?
Created an array of TextViews:
TextView[] tvs = new TextView[7];
tvs[0] = textView23;
tvs[1] = textView33;
tvs[2] = textView43;
tvs[3] = textView53;
tvs[4] = textView63;
tvs[5] = textView73;
tvs[6] = textView83;
Sorted the array and assinged new values to the TextViews:
Arrays.sort(tvs, new TVTextComparator());
textView23.setText(tvs[0].getText().toString());
textView33.setText(tvs[1].getText().toString());
textView43.setText(tvs[2].getText().toString());
textView53.setText(tvs[3].getText().toString());
textView63.setText(tvs[4].getText().toString());
textView73.setText(tvs[5].getText().toString());
textView83.setText(tvs[6].getText().toString());
And here is the Comporator class:
public class TVTextComparator implements Comparator<TextView> {
public int compare(TextView lhs, TextView rhs) {
Integer oneInt = Integer.parseInt(lhs.getText().toString());
Integer twoInt = Integer.parseInt(rhs.getText().toString());
return oneInt.compareTo(twoInt);
}
}
to sort your textViews, first put them in an array,
TextView[] tvs = new TextView[7];
tvs[0] = textView23;
tvs[1] = textView33;
// and so on
note that if you have handle to the parent container, you could easily build the array by using ViewGroup.getChildCount() and getChildAt().
now write a comparator for a text view,
class TVTextComparator implements Comparator<TextView> {
#Override
public int compare(TextView lhs, TextView rhs) {
return lhs.getText().toString().compareTo(rhs.getText().toString());
// should check for nulls here, this is NOT a robust impl of compare()
}
}
now use the comparator to sort the array,
Arrays.sort(tvs, 0, tvs.length, new TVTextComparator());
public void sortNumbers(View v) {
String[] numbers = new String[7];
numbers[0] = textView23.getText().toString();
numbers[1] = textView33.getText().toString();
numbers[2] = textView43.getText().toString();
numbers[3] = textView53.getText().toString();
numbers[4] = textView63.getText().toString();
numbers[5] = textView73.getText().toString();
numbers[6] = textView83.getText().toString();
Integer[] intValues = new Integer[numbers.length];
for (int i = 0; i < numbers.length; i++) {
intValues[i] = Integer.parseInt(numbers[i].trim());
}
Collections.sort(Arrays.asList(intValues));
textView23.setText(intValues[0]);
textView33.setText(intValues[1]);
textView43.setText(intValues[2]);
textView53.setText(intValues[3]);
textView63.setText(intValues[4]);
textView73.setText(intValues[5]);
textView83.setText(intValues[6]);
}

Categories

Resources