Android URI in OnClickListener - android

Hi guy's i have a problem with Android...
This is a part of my code:
setContentView(R.layout.activity_main);
TableLayout MainTable = (TableLayout) findViewById(R.id.main_table);
JSONArray Jobj = new JSONArray(result_set);
String url_img = null;
String url_video = null; //MUST CONTAINS THE URL OF MY VIDEO
for (int i = 0; i < Jobj.length(); i++) {
TableRow row = new TableRow(getApplicationContext());
row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
row.setPadding(0, 14, 2, 14);
JSONObject titoli = Jobj.getJSONObject(i);
Integer id = titoli.getInt("id_video");
String titolo = titoli.getString("nome_video");
String immagini = titoli.getString("video_img");
String video_url = titoli.getString("url_video");
/* video_url : this is the variable that i change (and contains the relative path that i obtains parsing json array) */
Pattern p = Pattern.compile("^(https?|ftp|file)://[-a-zA-Z0-9+&##/%?=~_|!:,.;]*[-a-zA-Z0-9+&##/%=~_|]");
Matcher m = p.matcher(immagini);
Pattern v = Pattern.compile("^/video/[-a-zA-Z0-9+&##/%?=~_|!:,.;]*[-a-zA-Z0-9+&##/%=~_|]");
Matcher vm = v.matcher(video_url);
// Path video
if (vm.matches() == false) {
url_video = path_youtube + video_url; // SECOND ERROR HERE
} else if (vm.matches() == true) {
url_video = path_an_tv + video_url; // SECOND ERROR HERE
}
// Path image
if (m.matches() == false) {
url_img = path + immagini;
} else if (m.matches() == true) {
url_img = immagini;
}
ImageView img = new ImageView(getApplicationContext());
img.setAdjustViewBounds(true);
img.setMaxHeight(140);
img.setMaxWidth(140);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(url_img).getContent());
img.setImageBitmap(bitmap);
LayoutParams params = new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
final TextView txt = new TextView(getApplicationContext());
txt.setGravity(Gravity.LEFT | Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
txt.setLayoutParams(params);
txt.setTextSize(18);
txt.setBackgroundColor(Color.WHITE);
txt.setTypeface(null, Typeface.BOLD);
txt.setTextColor(Color.BLACK);
txt.setId(id);
txt.setText(titolo);
txt.setClickable(true);
row.addView(img);
row.addView(txt);
MainTable.addView(row);
txt.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url_video)));
/* FIRST ERROR HERE, url_video contains the absolute url of my video*/
}
});
}
When i try compile my project an error occours:
*Cannot refer to a non final variable url_video inside a innner class defined in a different method...*
If I change url video into final another error occours:
The final local variable cannot be assigned. it must be blank and not using a compound assignment
How I can fix it ?
UPDATE I FIX IT REPLACING WITH THIS:
final TextView txt = new TextView(getApplicationContext());
txt.setGravity(Gravity.LEFT | Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL );
txt.setLayoutParams(params); txt.setTextSize(18); txt.setBackgroundColor(Color.WHITE);
txt.setTypeface(null, Typeface.BOLD); txt.setTextColor(Color.BLACK);
txt.setId(id); txt.setTag(url_video); txt.setText(titolo); txt.setClickable(true);
row.addView(img);
row.addView(txt);
MainTable.addView(row);
txt.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse((String) txt.getTag())));
}
});
}

Define it in class level private String video_url;
You can't access a variable defined within onCreate() within OnClick() Because the scope of oncreate is over when you get a click. So you must keep the variable scope alive.
UPDATE
Yeah, Its simple,
public class YourClass {
private String video_url;
public void OnCreate()
{
}
}

Just make this an instance variable
String url_video = null;
That is define this inactivity.

Related

Error on placing a URL on Picasso library on loading an image on an imageview in android

I'm having an error on loading the image from the server and displaying it using the Picasso library, I have a JSON string and it has a field of "img" => "whateverimageofanarticle.jpg", where in the value of that column on a JSON String may vary according to the content of the database. I can get the imagepath given by the JSON string, and display it on a textview but when I place it on the parameter of the .load() method in the Picasso Library, it does not work and stopped the execution of my app :(
Anyway, I'm using fragments instead of library for easier and faster execution of the application (I don't know if fragments matters on my problem), also the code is in the postExecute method of the asynctask, where in the onPostExecute() was overriden. Here is my exact code and my whole code.
ImageView banner = new ImageView(getActivity().getApplicationContext());
banner.getLayoutParams().height = 50;
banner.getLayoutParams().width = 80;
banner.requestLayout();
Picasso.with(getActivity().getApplicationContext())
.load("http://rtu-astronet.com/emag/"+_jsonObject.optString("img").toString())
.into(banner);
Whole code:
public class CollegeBulletinListFragment extends Fragment implements OnClickListener, Connector.OnPostExecuteListener{
public CollegeBulletinListFragment(){
}
TextView kem;
TextView headlinehead;
TextView shortdesc;
TextView headlinesender;
LinearLayout llist;
ImageButton img;
ProgressBar pbColBul;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_collegebulletinlist, container, false);
kem = (TextView) rootView.findViewById(R.id.mon_title);
img = (ImageButton) rootView.findViewById(R.id.imageButton1);
pbColBul = (ProgressBar) rootView.findViewById(R.id.pBcollegebul);
img.setOnClickListener(this);
headlinehead = (TextView) rootView.findViewById(R.id.mon_head_title);
shortdesc = (TextView) rootView.findViewById(R.id.mon_head_desc);
headlinesender = (TextView) rootView.findViewById(R.id.mon_head_sender);
String c = getArguments().getString("passingWord");
llist = (LinearLayout) rootView.findViewById(R.id.lllist);
int colval = this.setTextAndColorsToHead(c);
pbColBul.setVisibility(ProgressBar.VISIBLE);
//Execute items on scroll view
String secondFlag = "list";
Connector connect= new Connector(getActivity().getApplicationContext(),colval,secondFlag,0,0,0,"","");
connect.setOnPostExecuteListener(this);
connect.execute("");
return rootView;
}
public int setTextAndColorsToHead(String arg){
int collegeval = 0;
if (arg.equals("GN")){
kem.setText("General News");
} else if (arg.equals("CCS")){
kem.setText("College of Computer Studies");
collegeval = 1;
} else if (arg.equals("COE")){
kem.setText("College of Engineering");
collegeval = 2;
} else if (arg.equals("COED")){
kem.setText("College of Education");
collegeval = 4;
} else if (arg.equals("CON")){
kem.setText("College of Nursing");
collegeval = 3;
} else if (arg.equals("CBA")){
kem.setText("College of Business and Accountancy");
collegeval = 5;
} else if (arg.equals("CAS")){
kem.setText("College of Arts and Sciences");
collegeval = 6;
} else if (arg.equals("CIHM")){
kem.setText("College of International and Hospitality Management");
collegeval = 7;
}
return collegeval;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SpecificArticleFragment spcf = new SpecificArticleFragment();
Bundle args = new Bundle();
String tag = arg0.getTag().toString();
args.putString("art_id",tag);
spcf.setArguments(args);
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.content_frame, spcf).commit();
}
#Override
public void onPostExecute(String result) {
//headlinehead.setText(result);
try{
JSONObject jsonRootObj = new JSONObject(result);
JSONArray jsonArray = jsonRootObj.optJSONArray("Data");
JSONObject jsonObject = jsonArray.getJSONObject(0);
//code for headline
this.headlinehead.setText(jsonObject.optString("title").toString());
this.shortdesc.setText(jsonObject.optString("shortdesc").toString());
this.headlinesender.setText(jsonObject.optString("penname").toString());
this.img.setTag(jsonObject.optString("id").toString());
//code for headline
for (int p = 1; p < jsonArray.length(); p++){
JSONObject _jsonObject = jsonArray.getJSONObject(p);
LinearLayout conteach = new LinearLayout(getActivity().getApplicationContext());
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
conteach.setLayoutParams(lp);
conteach.setOrientation(LinearLayout.VERTICAL);
ImageView banner = new ImageView(getActivity().getApplicationContext());
banner.getLayoutParams().height = 50;
banner.getLayoutParams().width = 80;
banner.requestLayout();
Picasso.with(getActivity().getApplicationContext())
.load("http://rtu-astronet.com/emag/"+_jsonObject.optString("img").toString())
.into(banner);
TextView art_title = new TextView(getActivity().getApplicationContext());
art_title.setText(_jsonObject.optString("title").toString());
art_title.setTextSize(20);
art_title.setLayoutParams(new LayoutParams(350,LayoutParams.WRAP_CONTENT));
TextView art_shortdesc = new TextView(getActivity().getApplicationContext());
art_shortdesc.setText(_jsonObject.optString("shortdesc").toString());
art_shortdesc.setTextSize(14);
art_shortdesc.setTypeface(null, Typeface.ITALIC);
art_shortdesc.setLayoutParams(new LayoutParams(350,LayoutParams.WRAP_CONTENT));
TextView art_sender = new TextView(getActivity().getApplicationContext());
art_sender.setText("Written by: " + _jsonObject.optString("sender").toString());
art_sender.setTextSize(14);
art_sender.setLayoutParams(new LayoutParams(350,LayoutParams.WRAP_CONTENT));
art_sender.setPadding(0, 0, 0, 15);
conteach.addView(art_title);
conteach.addView(art_shortdesc);
conteach.addView(art_sender);
conteach.setTag(_jsonObject.optString("id").toString());
conteach.setClickable(true);
conteach.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SpecificArticleFragment spcf = new SpecificArticleFragment();
Bundle args = new Bundle();
args.putString("art_id", v.getTag().toString());
spcf.setArguments(args);
FragmentManager ft = getFragmentManager();
ft.beginTransaction().replace(R.id.content_frame, spcf).commit();
}
});
this.llist.addView(conteach);
}
this.pbColBul.setVisibility(ProgressBar.GONE);
} catch(JSONException e){
}
}
}
Problem solved, I just change
banner.getLayoutParams().height = 50;
banner.getLayoutParams().width = 80;
banner.requestLayout();
to
banner.setLayoutParams() and set the layout width and height , also I inserted an initial image for the imageview that will going to change after the doInBackground() method

How to get values from EditText created in Android

i mean editText created programmatically. I want to get the data inputted from those editText i created.
These are i've done so far.
VARIABLES
private GridLayout gridLayout;
//for tasks
int rowIndex = 2;
int colIndex = 1;
int rowIndex2 = 2;
int colIndex2 = 0;
int i=0;
int j=0;
//database variables
MyDBAdapter dbhandler;
To be able to create an editText in a gridlayout by a button click.
When "add new Task" button is clicked:
public void addTask(View view) {
i++;
Map<String, Integer> idsMap = new HashMap<String, Integer>();
String tname = "task" + Integer.toString(i);
EditText editText = new EditText(this);
GridLayout.LayoutParams param = new GridLayout.LayoutParams();
param.height = ViewGroup.LayoutParams.WRAP_CONTENT;
param.width = GridLayout.LayoutParams.MATCH_PARENT;
param.rowSpec = GridLayout.spec(rowIndex);
param.columnSpec = GridLayout.spec(colIndex);
editText.setTextColor(Color.BLACK);
editText.setBackgroundResource(android.R.drawable.edit_text);
editText.setText(tname);
editText.setLayoutParams(param);
TextView textView = new TextView(this);
GridLayout.LayoutParams param2 = new GridLayout.LayoutParams();
param2.rowSpec = GridLayout.spec(rowIndex2);
param2.columnSpec = GridLayout.spec(colIndex2);
textView.setPadding(30, 0, 0, 0);
textView.setTextColor(Color.BLACK);
textView.setTypeface(Typeface.DEFAULT_BOLD);
textView.setLayoutParams(param2);
if (rowIndex > 1) {
textView.setText("TASK "+Integer.toString(i)+": ");
editText.setId(i);
idsMap.put(tname, i);
}
gridLayout.addView(editText);
gridLayout.addView(textView);
rowIndex++;
rowIndex2++;
this.j = 0;
}
When "Add new Subtask" button is clicked:
public void addSubtask(View view) {
j++;
Map<String, Integer> idsMap = new HashMap<String, Integer>();
String taskno = "task" + Integer.toString(i) + "subtask" + Integer.toString(j);
EditText editText = new EditText(this);
GridLayout.LayoutParams param = new GridLayout.LayoutParams();
param.height = ViewGroup.LayoutParams.WRAP_CONTENT;
param.width = GridLayout.LayoutParams.MATCH_PARENT;
param.rowSpec = GridLayout.spec(rowIndex);
param.columnSpec = GridLayout.spec(colIndex);
editText.setTextColor(Color.BLACK);
editText.setBackgroundResource(android.R.drawable.edit_text);
editText.setText(taskno);
editText.setLayoutParams(param);
TextView textView = new TextView(this);
GridLayout.LayoutParams param2 = new GridLayout.LayoutParams();
param2.rowSpec = GridLayout.spec(rowIndex2);
param2.columnSpec = GridLayout.spec(colIndex2);
textView.setPadding(30,0,0,0);
textView.setTextColor(Color.BLACK);
textView.setLayoutParams(param2);
if (rowIndex > 1) {
textView.setText("Subtask "+Integer.toString(j)+": ");
editText.setId(j);
idsMap.put(taskno, j);
}
gridLayout.addView(editText);
gridLayout.addView(textView);
rowIndex++;
rowIndex2++;
}
IT WOULD LOOK LIKE THIS FOR EXAMPLE:
TASK 1: ___________
Subtask 1: ________
Subtask 2: ________
TASK 2: ___________
Subtask 1: ________
TASK 3: ___________
Assuming the user is done inputting the necessary info and clicks the submit button. THE PROBLEM COMES IN. I DONT KNOW HOW TO GET ALL THE VALUES BASED on the number of editText created by the user.
public void submit(){
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//implementation
String task1 = task1.getText().toString(); // It would only get task1
String subtask1 = task1subtask1.getText().toString(); // It would only get subtask1 of task 1
}
}
That kind of implementation is not usable since i dont know how many editTexts of tasks and subtasks that the user created. HELPPPP T___T
Every time you create an Edit Text use View.generateId() to generate an ID, store that ID in an HashMap or loop your container Views with getChildAt() and then, if its an EditText get its value.
Maybe you can set a custom tag for each edittext that you create.
You can determinate a specific generic tag for "Task" and an other for "Subtask" and after each creation, you set the tag to your edittext like that :
edittext.setTag(KEY, "task_X") where X is a incremental id.
After that, you can enumerate all children of your main container and check tags'children
List<EditText> allEdittext = new ArrayList<EditText>();
public void addSubtask(View view) {
j++;
Map<String, Integer> idsMap = new HashMap<String, Integer>();
String taskno = "task" + Integer.toString(i) + "subtask" + Integer.toString(j);
EditText editText = new EditText(this);
GridLayout.LayoutParams param = new GridLayout.LayoutParams();
param.height = ViewGroup.LayoutParams.WRAP_CONTENT;
param.width = GridLayout.LayoutParams.MATCH_PARENT;
param.rowSpec = GridLayout.spec(rowIndex);
param.columnSpec = GridLayout.spec(colIndex);
editText.setTextColor(Color.BLACK);
editText.setBackgroundResource(android.R.drawable.edit_text);
editText.setText(taskno);
editText.setLayoutParams(param);
TextView textView = new TextView(this);
GridLayout.LayoutParams param2 = new GridLayout.LayoutParams();
param2.rowSpec = GridLayout.spec(rowIndex2);
param2.columnSpec = GridLayout.spec(colIndex2);
textView.setPadding(30,0,0,0);
textView.setTextColor(Color.BLACK);
textView.setLayoutParams(param2);
if (rowIndex > 1) {
textView.setText("Subtask "+Integer.toString(j)+": ");
editText.setId(j);
idsMap.put(taskno, j);
}
allEdittext.add(editText);
gridLayout.addView(editText);
gridLayout.addView(textView);
rowIndex++;
rowIndex2++;
}
Then your get the values from the edit text
public void submit(){
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//implementation
String task1 = task1.getText().toString(); // It would only get task1
//i will be the position
String subtask1 = allEdittext.get(i).getText().toString();// It would only get subtask1 of task 1
}
}
Like this you can modify the code for addtask() function

Adding onClickListener for a button created dynamically within a for loop

I have a RelativeLayout that allows players of a game to input personal details such as name and define their role. The Layouts are created dynamically depending on how many players there are (This is defined earlier in the activity).
This is all contained in a for loop to generate each layout.
I am trying to add an onclicklistener so that as each player enters their details their individual data will be stored.
The code I have used so far produces an ArrayIndexOutOfBoundsException.
Could you please explain how I should correct this code, thanks.
public void buildDynamicViews(Integer input1) {
int textId = 10;
//Arrays
groupDetailsList = (RelativeLayout)findViewById(R.id.playersNameLayout);
row_Number = new TextView[input1];
spinnerArray = new Spinner[input1];
groupDetailsContainer = new RelativeLayout[input1];
firstNameText = new TextView[input1];
lastNameText = new TextView[input1];
fNameInput = new EditText[input1];
lNameInput = new EditText[input1];
playerDetailsButton = new Button[input1];
//displays lines of text with instructions
text = (TextView)findViewById(R.id.displayMessage);
ViewGroup.LayoutParams params = text.getLayoutParams();
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
text.setId(textId);
((MarginLayoutParams) params).setMargins(0,0,0,20);
text.setLayoutParams(params);
String txt1 = getResources().getString(R.string.player_details_Title);
String txt2 = getResources().getString(R.string.players_details_message);
String txt = txt1+"\n"+txt2;
text.setText(txt);
//Scrollview to contain relativeLayouts created in for loop
ScrollView scroll = (ScrollView)findViewById(R.id.playerNameScroller);
RelativeLayout.LayoutParams scrollerLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
scrollerLayoutParams.addRule(RelativeLayout.BELOW, text.getId());
scroll.setLayoutParams(scrollerLayoutParams);
//Loop
for ( i = 0; i < input1; i++) {
//generate relativelayout to house each individual players data input section
groupDetailsContainer[i] = new RelativeLayout(this);
groupDetailsContainer[i].setId(20+i);
RelativeLayout.LayoutParams containerParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
if(i==0){
containerParams.addRule(RelativeLayout.BELOW ,text.getId());
}
else
{
containerParams.addRule(RelativeLayout.BELOW, (i+19));
}
containerParams.setMargins(0,0,0,20);
groupDetailsContainer[i].setLayoutParams(containerParams);
//generate left hand box for player number
row_Number[i]= new TextView(this);
LayoutParams rowNumParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
rowNumParams.addRule(RelativeLayout.ALIGN_LEFT);
if(i ==0)
rowNumParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
else
{
rowNumParams.addRule(RelativeLayout.BELOW, (i-1));
}
row_Number[i].setLayoutParams(rowNumParams);
row_Number[i].setText("Details for Player Number:" + (i+1));
row_Number[i].setHeight(80);
row_Number[i].setTextSize(20);
row_Number[i].setWidth(125);
row_Number[i].setId((i+1));
//generate box for text first name
RelativeLayout.LayoutParams fNameParams = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
fNameParams.addRule(RelativeLayout.RIGHT_OF, row_Number[i].getId() );
firstNameText[i] = new TextView(this);
firstNameText[i].setTextSize(20);
firstNameText[i].setHeight(40);
firstNameText[i].setText("Enter First Name:");
firstNameText[i].setId(31*(i+1));
firstNameText[i].setLayoutParams(fNameParams);
//generate EditTextbox for first name input
RelativeLayout.LayoutParams fNameinputParams = new LayoutParams(200, 25);
fNameinputParams.addRule(RelativeLayout.RIGHT_OF, firstNameText[i].getId());
fNameinputParams.addRule(RelativeLayout.ALIGN_BASELINE, firstNameText[i].getId());
fNameinputParams.setMargins(10, 0, 10, 0);
fNameInput[i] = new EditText(this);
fNameInput[i].setLayoutParams(fNameinputParams);
fNameInput[i].setId(32*(i+1));
fNameInput[i].setTextSize(20);
//generate button
RelativeLayout.LayoutParams detailsButtonParams = new LayoutParams (LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
playerDetailsButton[i] = new Button(this);
detailsButtonParams.addRule(RelativeLayout.RIGHT_OF, spinnerArray[i].getId());
detailsButtonParams.addRule(RelativeLayout.ALIGN_BOTTOM, spinnerArray[i].getId());
detailsButtonParams.setMargins(20, 0, 20, 0);
playerDetailsButton[i].setLayoutParams(detailsButtonParams);
playerDetailsButton[i].setWidth(250);
playerDetailsButton[i].setHeight(20);
playerDetailsButton[i].setText("Press to save details");
//generate OnClick Listener for button
PlayerDetailsButtonOnClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
String FName = firstNameText[i].toString();
String LName = lastNameText[i].toString();
String fullName = FName+" "+LName;
toast(fullName);
}
};
playerDetailsButton[i].setOnClickListener(PlayerDetailsButtonOnClick);
//wrap each view to the layout
groupDetailsContainer[i].addView(row_Number[i]);
groupDetailsContainer[i].addView(fNameInput[i]);
groupDetailsContainer[i].addView(lNameInput[i]);
groupDetailsContainer[i].addView(firstNameText[i]);
groupDetailsContainer[i].addView(lastNameText[i]);
groupDetailsContainer[i].addView(spinnerArray[i]);
groupDetailsContainer[i].addView(playerDetailsButton[i]);
groupDetailsList.addView(groupDetailsContainer[i]); }
One issue may also be how to pass the string values from the loop into the onClick() function. Thanks
The pojo class is a simple class (you can add the data trough the setters or make a simple constructor):
private class POJOName {
String firstName;
String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
this class can be used to store the first name and also the last name and then you use playerDetailsButton[i].setTag( here you put the pojo object ); and then
//generate OnClick Listener for button
PlayerDetailsButtonOnClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
POJOName pojo = (POJOName)v.getTag();
String fullName = pojo.getFirstName()+" "+pojo.getLastName();
toast(fullName);
}
};
I also managed to solve this a second way as well.
I assigned a final int j variable to the int i value within the for loop.
Then in the OnClick() I referenced the relevant editview like this [class].this.[viewname][j].gettext().toString();
So my code looks like this:
final int j = i;
playerDetailsButton[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("detailsOnClick", "Button Pressed");
inputFName = GroupDetails1.this.fNameInput[j].getText().toString();
Log.d("inputFNameOnClick", inputFName);
inputLName = (GroupDetails1.this.lNameInput[j].getText()).toString();
toast(inputFName);
toast(inputLName);
}
Thanks for all your help and input

working with canvas : The specified child already has a parent. You must call removeView() on the child's parent first

I visit so many solutions regarding this issue but can't catch it clearly .When ever I run the project first time it works perfectly but when I run it second time then it fire this error in logCat
The specified child already has a parent. You must call removeView() on the child's parent first
where is the error in that code segment ?where should I change in code. any suggestion is acceptable .Thanks in advance ..
Main.java
public class MainActivity extends Activity {
List<PieDetailsItem> piedata = new ArrayList<PieDetailsItem>(0);
EditText edt3;
Button btnChart;
public String s15;
public String[] strArray;
public ImageView mImageView ;
public LinearLayout finalLayout ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
finalLayout = (LinearLayout) findViewById(R.id.pie_container);
mImageView = new ImageView(this);
edt3 = (EditText) this.findViewById(R.id.editText1);
btnChart = (Button) findViewById(R.id.button1);
btnChart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*if(mImageView != null) {
finalLayout.removeView(mImageView);
}
else {*/
s15 = edt3.getText().toString();
/*System.out.println("value 1 is --->"+s10);
System.out.println("value 2 is --->"+s12);*/
System.out.println("value 3 is --->"+s15);
String domain = s15;
strArray = domain.split("\\,");
for (String str : strArray) {
System.out.println(str);
}
// }
openChart();
}
});
}
private void openChart(){
Integer[] items = new Integer[strArray.length];
//double[] distribution = new double[strArray.length];
for (int i = 0; i < items.length; i++) {
items[i] = Integer.parseInt(strArray[i]);
System.out.println("xxxxxx"+items[i]);
}
PieDetailsItem item;
int maxCount = 0;
int itemCount = 0;
// int items[] = { 20, 40, 10, 15, 5 };
int colors[] = { -6777216, -16776961, -16711681, -12303292, -7829368 };
// String itemslabel[] = { " vauesr ur 100", " vauesr ur 200",
// " vauesr ur 300", " vauesr ur 400", " vauesr ur 500" };
for (int i = 0; i < items.length; i++) {
itemCount = items[i];
item = new PieDetailsItem();
item.count = itemCount;
// item.label = itemslabel[i];
item.color = colors[i];
piedata.add(item);
maxCount = maxCount + itemCount;
}
int size = 200;
int BgColor = 0xffa11b1;
Bitmap mBaggroundImage = Bitmap.createBitmap(size, size,
Bitmap.Config.ARGB_8888);
View_PieChart piechart = new View_PieChart(this);
piechart.setLayoutParams(new LayoutParams(size, size));
piechart.setGeometry(size, size, 2, 2, 2, 2, 2130837504);
piechart.setSkinparams(BgColor);
piechart.setData(piedata, maxCount);
piechart.invalidate();
piechart.draw(new Canvas(mBaggroundImage));
piechart = null;
//ImageView mImageView = new ImageView(this);
mImageView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
mImageView.setBackgroundColor(BgColor);
mImageView.setImageBitmap(mBaggroundImage);
//LinearLayout finalLayout = (LinearLayout) findViewById(R.id.pie_container);
finalLayout.addView(mImageView);
}
}
You're adding mImageView to the layout multiple times. A view can only be part of 1 ViewGroup. You need to either add it only once, or create a second ImageView if you really want 2 of them in the layout.

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

Categories

Resources