Identify a specific dynamically generated TextView in order to setText - android

I have a function that generates a specific number of TextViews dynamically.
TextView tv;
EditText et;
public TextView textViewGenerate(final Activity activity, String tag, Integer id) {
tv = new TextView(activity);
GradientDrawable gd = new GradientDrawable();
gd.setColor(0xFFFFFF);
gd.setCornerRadius(4);
gd.setStroke(1, 0xFF757575);
tv.setBackground(gd);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT,
1.0f
);
tv.setPadding(7, 9, 0, 0);
tv.setGravity(Gravity.START);
tv.setTextSize(22);
tv.setTag(tag);
tv.setId(id);
tv.setHint("Enter Module Serial Number");
//Click to launch camera
tv.setClickable(true);
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Intent intent = new Intent(ct, MctCameraActivity.class);
Intent intent = new Intent(activity, MctCameraActivity.class);
activity.startActivityForResult(intent, 1);
//ct.startActivity(intent);
//ToDo: finish receiving the data from the activityForResult
}
});
lp.setMargins(10, 0, 10, 0);
lp.setMarginStart(10);
lp.setMarginEnd(10);
tv.setLayoutParams(lp);
return tv;
}
}
The onClick launches another activity that loads the camera in order to capture barcode data. In the main activity I create the TextViews with
final LayoutElements le = new LayoutElements();
mainLayout = (LinearLayout)findViewById(R.id.mctScanPageMain);
for(int i = 0; i < 3; i++) {
mainLayout.addView(le.textViewGenerate(this, "NewID" + i, i));
}
The onActivityResult returns the value from the camera activity but the issue is that it sets every generated TextView to have the same barcode number (the barcode number is returned as a string). How can I modify this so that only the text of the selected TextView gets changed in the onActivityResult?
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == RESULT_OK && data != null) {
String returnResult = data.getStringExtra("result");
for (int i=0; i < mainLayout.getChildCount(); i++){
TextView tv = (TextView) mainLayout.findViewWithTag("NewID"+i);
if(tv == null) {
break;
} else {
tv.setText(returnResult);
}
}
}
}

In your click listener of TextView you can change:
Intent intent = new Intent(activity, MctCameraActivity.class);
activity.startActivityForResult(intent, 1);
to
Intent intent = new Intent(activity, MctCameraActivity.class);
intent.putExtra("text_view_tag", tag);
activity.startActivityForResult(intent, 1);
And then sent it back in result of MctCameraActivity, so you can use it in onActivityResult with getStringExtra. This way you will know tag of TextView which started activity.
Alternatively you can use requestCode that you pass to startActivityForResult to differentiate between text views. For example pass request code 1 for text view 1, request code 2 for text view 2 etc and use this requestCode in onActivityResult.

Related

Startactivity for result with causes crash

I am trying to learn Android Studio and my first app is a blood alcohol calculator. The user starts that app and then a new activity is started so that they can enter their weight and press ok, this returns them back to the main activity and fills in the weight text.
I use startActivityForResult and then putExtra in the second activity. The first activity crashes if I use the getExtra method, if I delete the 2 receiving lines of code then there is no crash. When I use the debugger it says NullPointerException just before it says App has stopped working
Main activity code
public class MainActivity extends Activity {
static int displayunit = 0;
static double percentage = 5.0;
static int change = 1;
static double bah;
static double vol = 25;
static double timestamp = 0;
static double w = 0;
static String we = "a";
final int rcode = 3;
final String[] units = {"Small Shot(25ml)", "Large Shot(35ml)", "Small
Port/Sherry(50ml)", "Large Port/Sherry(70ml)", "Small Wine(125ml)",
"Large
Wine(175ml)", "Small Beer Bottle(284ml)", "Half Pint(236.6ml)", "Medium
Beer Bottle(330ml)", "Can of beer(440ml)", "Large Bottle(500ml)",
"Pint(568.26ml)", "Massive Beer Bottle(660ml)"};
final int[] unitsum = {25, 35, 50, 70, 125, 175, 284, 237, 330, 440, 500,
569, 660};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent();
intent.setClassName("com.example.alccalc","com.example.alccalc.enterweight");
if(w ==0){
startActivityForResult(intent, rcode);
}
}
#Override
protected void onActivityResult ( int requstCode, int resultCode,
Intent intent){
if (requstCode == rcode && resultCode == RESULT_OK) {
we = getIntent().getStringExtra("weighttext");
w = Double.parseDouble(we);
}
TextView kg = (TextView) findViewById(R.id.kg);
kg.setText(we)
Second Activity
public class enterweight extends Activity {
EditText entweight;
TextView tester;
String weightstring;
#Override
protected void onCreate(Bundle State) {
super.onCreate(State);
setContentView(R.layout.activity_enterweight);
entweight = (EditText) findViewById(R.id.entweight);
tester = (TextView)findViewById(R.id.tester);
Button okweight = (Button) findViewById(R.id.okweight);
okweight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
weightstring = entweight.getText().toString();
//tester.setText(weightstring);
Intent intent = new Intent();
intent.putExtra
("weighttext", weightstring);
setResult(RESULT_OK, intent);
if (intent.hasExtra("weighttext")) {
finish();
}
}
});
}
}
The error is here getIntent();
Since you are using the onActivityResult ( int requstCode, int resultCode,
Intent intent) method, you can find your extras in the variable intent. The method getIntent() returns the intent that is used to start the activity. In your case it is null.
Use:
we = intent.getStringExtra("weighttext");
instead of
we = getIntent().getStringExtra("weighttext");
Better:
Bundle extras = intent.getExtras();
if (extras != null) {
String result = extras.getString("weighttext");
.....
}
Try this in your receiving code
Intent intent= getIntent();
Bundle b = intent.getExtras();
if(b != null)
we = b.getString("weighttext");
You are calling getIntent() to get the result data. getIntent() is an activity method that returns an intent that is used to start the activity. You should use the intent variable that is passed on onActivityResult method.
if (requstCode == rcode && resultCode == RESULT_OK) {
we = intent.getStringExtra("weighttext");
w = Double.parseDouble(we);
}

How to check imageview is empty or not where imageview created programmatically in android

I created image view programatically, and need check image view is empty or not.
getdrawable(),getHeigt() and getwidth() methodes but it is not working for me.
Imageview created like this:
ImageView iv = new ImageView(this);
code:
public void dynamicTable(String alist[]) throws NullPointerException {
try {
TableLayout tl = (TableLayout) findViewById(R.id.main_table1);
tl.setBackgroundColor(Color.GRAY);
sizelen = alist.length;
cam = new Button[sizelen];
iv = new ImageView[sizelen];
int k;
for (k = 0; k < sizelen; k++) {
try {
final int j = k;
TableRow tr_head = new TableRow(this);
TableLayout.LayoutParams rowparams = new TableLayout.LayoutParams(
TableLayout.LayoutParams.FILL_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT);
int leftMargin = 2;
int topMargin = 1;
int rightMargin = 2;
int bottomMargin = 1;
rowparams.setMargins(leftMargin, topMargin, rightMargin,
bottomMargin);
rowparams.weight = (float) 0.5;
tr_head.setLayoutParams(rowparams);
// tr_head.setId(10);
tr_head.setBackgroundColor(Color.WHITE);
/*
* tr_head.setLayoutParams(new LayoutParams(
* LayoutParams.FILL_PARENT LayoutParams.WRAP_CONTENT));
*/
cam[k] = new Button(this);
cam[k].setText(alist[k]);
cam[k].setTextColor(Color.WHITE);
cam[k].setBackgroundColor(Color.parseColor("#ffab00"));
cam[k].setClickable(true);
cam[k].setFocusable(true);
cam[k].setGravity(Gravity.LEFT);
cam[k].setMaxLines(2);
cam[k].setPadding(10, 10, -10, 10);
cam[k].setAllCaps(false);
cam[k].setTextSize(13);
cam[k].setLayoutParams(new TableRow.LayoutParams(85,
TableLayout.LayoutParams.WRAP_CONTENT));
// cam[i].setWidth(150);
// cam[i].setEms(0);
// cam[i].setGravity(25);
// cam[i](Gravity.LEFT);
// cam[i].setLayoutParams(params);
cam[k].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
cam[j].setBackgroundColor(Color.GRAY);
camera(j);
}
});
tr_head.addView(cam[k]); // add the column to the table row
// here
iv[k] = new ImageView(this);
iv[k].setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT));
iv[k].setPadding(0, 7, 10, 0);
iv[k].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
imageviewOnclick(iv[j]);
}
});
tr_head.addView(iv[k]); // dd the column to the table row
// here
tl.addView(tr_head, rowparams);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
These methods will take the photo from the phone and display it in an ImageView, i guess you can use this in your code to see if the photo shows up or not.
public void DisplayPhotoPreview(){
DisplayPhotoPreview = (Button)findViewById(R.id.UploadPhotoPreviewBtn);//Finds the button in design and put it into a button variable.
DisplayPhotoPreview.setOnClickListener(//Listens for a button click.
new View.OnClickListener() {//Creates a new click listener.
#Override
public void onClick(View v) {//does what ever code is in here when the button is clicked
switch (v.getId()) {//switches to the case if that .id. is clicked.
case R.id.UploadPhotoPreviewBtn://Does what ever the code is in the case if the upload button is clicked.
//I open up an intent variable and through different commands and I open up my gallery on my phone and i cant get
//out of the gallery until i choose a photo. Then I save the photo in the intent and call the onActivityResult() method which displays the image.
//Also a intent is how two activities can send data.
Intent ChoosePhotoFromGallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(ChoosePhotoFromGallery, RESULT_LOAD_IMAGE);//Stores the image into the variable.
break;
}
}
}
);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//so the if statement checks if the image came through, double checks if the result is okay and triple checks to see if the data is not null.
if(requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data != null){
//gets the address of the image/data !!!!!!ALSO CAN HOLD THE ADDRESS FOR THE SERVER!!!!!!.
Uri Image = data.getData();
ItemPhotoPreview = (ImageView)findViewById(R.id.ItemPhotoPreviewImageView);
//Sets the image into the variable and displays it
ItemPhotoPreview.setImageURI(Image);
}
}

ListView Items get reset onActivityResult from 2 different activities

I have a list view which contains a TextView for each list item. I need to take a picture onItemClick of the listView. onActivityResult of the ACTION_IMAGE_CAPTURE intent and updating the listview , I start another activity for result.
The problem I am facing is that all the textviews in my list view are getting reset when I come back to the activity onActivityResult from the second activity. Can you please help me with this.
This is my onItemClick
public void onItemClick(AdapterView<?> arg0, View v, int index, long arg3) {
selectedIndex = index; //selectedIndex is a class level variable
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = createImageFile();
if (f != null) {
imageFileName = f.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
}
startActivityForResult(takePictureIntent, 1);
}
}
This is my onActivityResult
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
View v = listView.getChildAt(selectedIndex
- listView.getFirstVisiblePosition());
TextView textView = (TextView) v.findViewById(R.id.textView1);
int quantity = Integer
.parseInt(textView.getText().toString().trim().length() > 0 ? quantityTV
.getText().toString() : getString(R.string._0));
quantity++;
textView.setText(String.valueOf(quantity));
listViewAdapter.notifyDataSetChanged();
Intent intent = new Intent();
intent.setClass(getApplicationContext(), NotificationActivity.class);
intent.putExtra("Value1", "0");
startActivityForResult(intent, 100);
}
else if (requestCode == 100) {
// do nothing
}
}
While you're updating the content of the text view here, you're not updating the data that backs the adapter for your list view. This means when your activity comes back into view (after the second startActivityForResult) it's redrawing itself with the old data.
Instead of updating the view directly, you should update the data that backs the adapter. Something like this; you'll have to modify it to suit your code.
if (requestCode == 1 && resultCode == RESULT_OK) {
List<Integer> adapterData = listViewAdapter.getQuantities();
int quantity = adapterData.get(selectedIndex) + 1;
adapterData.set(selectedIndex, quantity);
listViewAdapter.setQuantities(adapterData);
Intent intent = new Intent();
intent.setClass(getApplicationContext(), NotificationActivity.class);
intent.putExtra("Value1", "0");
startActivityForResult(intent, 100);
}
And in your adapter, you'd have something like this:
public List<Integer> getQuantities() {
return mQuantities;
}
public void setQuantities(List<Integer> quantities) {
mQuantities = quantities;
notifyDataSetChanged();
}

how update a textview

simple program: 2 buttons (previous/next) and a textview to show text.
by intent I created an Index (inside a method)
private void index(){
Intent i = new Intent(this, Index.class);
startActivityForResult(i, 1);
}
Index.class (with 3 buttons):
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String result = "1";
Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(RESULT_OK,returnIntent);
finish();
}
});
Main.class
String value = "1";
final String prog1[] = new String[16];
final String prog2[] = new String[105];
final String prog3[] = new String[66];
int a;
int b;
int c=3;
int array1start = 0; int array1end = 15;
int array2start = 0; int array2end = 105;
int array3start = 0; int array3end = 65;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
if (value.equals("1")){
a = array1start;
b = array1end;
prog=prog1;
}
else if (value.equals("2")){
a = array2start;
b = array2end;
prog=prog2;
textView1.setText(""+prog[a]);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
String result=data.getStringExtra("result");
value=result;
Toast toast2=Toast.makeText(this,"value: "+value,Toast.LENGTH_LONG);
toast2.show();
}
if (resultCode == RESULT_CANCELED) {
//Write your code on no result return
}}
}//onAcrivityResult
at this point, choosen choice in index class should be change a result string to "value" string in main class
private void index(){
Intent i = new Intent(this, Index.class);
startActivityForResult(i, 1);
}
my textview take data from array1 or array2 by index class
so, I dont' understand how update textview (because index value is correct).
thanks for the help
Put you code into function onActivityResult
if (value.equals("1")){
a = array1start;
b = array1end;
prog=prog1;
}
else if (value.equals("2")){
a = array2start;
b = array2end;
prog=prog2;
textView1.setText(""+prog[a]);

Passing data between activities - Android SDK

I have read the previously posted questions and answers for 2 days and I've tried every variation suggested as well as setting my launchMode attribute to "standard" in my manifest.
I'm trying to pass data from my second activity back to my first activity after pressing a button. After I press the button, the first activity is launched but it doesn't go back to my onActivityResult() method. I can't figure out why this is happening.
Here's my code from activity 2:
Button btnAdd = (Button) findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Check that message is printed out to LogCat
System.out.println("hello test1 Activity2");
EditText band = (EditText) findViewById(R.id.txtBand);
band.setFilters(new InputFilter[] {
new InputFilter.LengthFilter(9)
});
EditText album = (EditText) findViewById(R.id.txtAlbum);
album.setFilters(new InputFilter[] {
new InputFilter.LengthFilter(9)
});
final Spinner genre = (Spinner) findViewById(R.id.spin_genre);
TextView selection = (TextView)genre.getSelectedView();
CharSequence strBand = band.getText();
CharSequence strAlbum = album.getText();
CharSequence strGenre = selection.getText();
//Check that we got input values
System.out.println("hello test Activity2- " +
strBand + " - " + strAlbum + " - " + strGenre);
//**********Intent Declaration************
Intent i = new Intent(getApplicationContext(), Activity1.class);
i.putExtra("strBand", strBand);
i.putExtra("strAlbum", strAlbum);
i.putExtra("strGenre", strGenre);
startActivityForResult(i, 0);
setResult(RESULT_OK, i);
finish();
}
});
Here's activity 1:
public class Activity1 extends Activity {
/** Called when the activity is first created. */
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button addAlbum = (Button) findViewById(R.id.btnMain);
addAlbum.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent();
i.setClassName("jorge.jorge.jorge",
"jorge.jorge.jorge.Activity2");
startActivity(i);
}
});
}// end of onCreate()
//******************Callback Method****************************
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
//Checks if we got to ActivityResult
System.out.println("hello test 2: We got to Activity1");
if (resultCode == RESULT_OK)
{
Bundle returndata = data.getExtras();
String strAlbum = returndata.getString("strAlbum");
String strBand = returndata.getString("strBand");
String strGenre = returndata.getString("strGenre");
// check to see if we got the variable values from activity2
System.out.println("hello test 2: We got to Activity1 with variables - "
+ strBand + " - " + strAlbum + " - " + strGenre);
//Create table layout to contains views with variable values
TableLayout table = new TableLayout(this);
table.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
//creates row with parameters
TableRow row = new TableRow(this);
row.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
//text views to contain variable values
TextView tv1 = new TextView(this);
tv1.setText(strBand);
row.addView(tv1);
TextView tv2 = new TextView(this);
tv2.setText(strAlbum);
row.addView(tv2);
TextView tv3 = new TextView(this);
tv3.setText(strGenre);
row.addView(tv3);
//adds the table row to the table layout
table.addView(row);
}
}// end onActivityResult()
}
I'm not sure if my activity callbacks are not placed properly in the code or if I'm not firing the intent properly or if I'm not setting up the callback with the right method or what. I know this topics has been discussed but I'm out of ideas. Thanks.
You've just got it backwards. If Activity1 is supposed to startActivity2 and Activity2 is supposed to send the result back to Activity1, you need to do it like this:
in Activity1:
Intent i = new Intent();
i.setClassName("jorge.jorge.jorge", "jorge.jorge.jorge.Activity2");
startActivityForResult(i); // This starts Activity2 and waits for the result
in Activity2:
Intent i = new Intent(getApplicationContext(), Activity1.class);
i.putExtra("strBand", strBand);
i.putExtra("strAlbum", strAlbum);
i.putExtra("strGenre", strGenre);
setResult(RESULT_OK, i);
finish(); // This closes Activity2 and generates the callback to Activity.onActivityResult()

Categories

Resources