Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding scroll view to linear layout dynamically

i want to add scrollview in my activity, i have tried to add scrollview dynamically but it throws me an exception. i am newbie in android, i dont know much about this,

please look at the code:

    package com.example.ermanager;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import com.example.ermanager.R.drawable;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.Toast;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;

public class order extends Activity {
String text;
    private CheckBox chk;
        List<String> orderList = new ArrayList<String>();
        List<String> nameList = new ArrayList<String>();
        List<String> priceList = new ArrayList<String>();
        List<String> timeList = new ArrayList<String>();

        String wname=null;
         private AsyncTask<String, String, String> asyncTaskorder;


 private AsyncTask<String, String, String> asyncTask;
    private String response;
    private static Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_order);

     wname =waiter.getWaiter();

     Log.i("tag", "waiter name is "+wname);

     stopService(new Intent(getBaseContext(), notifcationService.class));

     GetDishesAsyncTask runner=new GetDishesAsyncTask();
    //dummy username and password just to avoid errors, no need
    String userName="a";
    String password="b";

    asyncTask=runner.execute(userName,password);
    String asyncResultText;
    try {
        asyncResultText = asyncTask.get();
          response = asyncResultText.trim();

          Log.i("tag", "dishes from server is "+response);

          //string prsing code started

          String name_string="";
        String price_string="";
        String time_string="";
        int name_counter=0;
        int price_counter=0;
        int time_counter=0;




        char [] ch_resp = response.toCharArray();


        //initial parsing for name sting...assining values to name_string

        for(int i=0; i<response.length(); i++)
        {

            if(ch_resp[i]=='*' && name_counter==0)
            {
                name_counter=1; 

            continue;
            }

            if(ch_resp[i]=='*' && name_counter==1)
            {
                break;
            }

            if(name_counter==1)
            {
                name_string=name_string+ch_resp[i];

            }

        }
        Log.i("tag", " first name array is "+name_string);


        //for price string

        response=response.replace("*"+name_string+"*", "");

        ch_resp = response.toCharArray();

        for(int i=0; i<response.length(); i++)
        {

            if(ch_resp[i]=='&' && price_counter==0)
            {
                price_counter=1;    

            continue;
            }

            if(ch_resp[i]=='&' && price_counter==1)
            {
                break;
            }

            if(price_counter==1)
            {
                price_string=price_string+ch_resp[i];

            }

        }

        Log.i("tag", " first lat array is "+price_string);




        response=response.replace("&"+price_string+"&", "");

        //initial parsing for time sting...assining values to time_string

        ch_resp = response.toCharArray();

        for(int i=0; i<response.length(); i++)
        {

            if(ch_resp[i]=='^' && time_counter==0)
            {
                time_counter=1; 

            continue;
            }

            if(ch_resp[i]=='^' && time_counter==1)
            {
                break;
            }

            if(time_counter==1)
            {
                time_string=time_string+ch_resp[i];

            }

        }

        Log.i("tag", " first longg array is "+time_string);

        String temp="";




        int count=0;

        char [] name_string1 = name_string.toCharArray();
        char [] price_string1 = price_string.toCharArray();
        char [] time_string1 = time_string.toCharArray();


        //***** parsing code for names

        char msg;

        // Log.i("tag", name_string);
         for(int i=0; i<name_string1.length; i++)
            {




                if(name_string1[i]==':')
                {
                    msg=name_string1[i];
                   Log.i("tag", "first time "+msg+" found");
                  // alert("first time "+name_string1[i]+" found");

                    for(int j=i+1; j<name_string1.length; j++)
                    {


                       // alert(" in j loop, j at "+name_string[j]);
                        if(name_string1[j]!=':')
                        {
                     // alert("in temp if");
                            temp=temp+name_string1[j];

                            Log.i("tag", "now temp is"+temp);
                        }

                        else if (name_string1[j]==':')
                        {   

                           msg=name_string1[j];
                     Log.i("tag", "else satisfied "+msg+" found");
                     Log.i("tag", "final name is "+temp);

                    nameList.add(temp);

                      Log.i("tag", "name list at count is"+nameList.get(count));
                       Log.i("tag", "count value is "+count);

                       //  alert("count at "+count+" and array is"+final_name_array[count]);
                            temp="";
                       count++;

                            i=j-1;
                            //alert(" name string of i is"+name_string[i]);
                            break;
                        }
                        }


                }

            }

         //***** parsing code for price
         count=0;


        // Log.i("tag", name_string);
         for(int i=0; i<price_string1.length; i++)
            {



                if(price_string1[i]==':')
                {
                    msg=price_string1[i];
                   Log.i("tag", "first time "+msg+" found");
                  // alert("first time "+name_string1[i]+" found");

                    for(int j=i+1; j<price_string1.length; j++)
                    {


                       // alert(" in j loop, j at "+name_string[j]);
                        if(price_string1[j]!=':')
                        {
                     // alert("in temp if");
                            temp=temp+price_string1[j];

                            Log.i("tag", "now temp is"+temp);
                        }

                        else if (price_string1[j]==':')
                        {   

                           msg=price_string1[j];
                     Log.i("tag", "else satisfied "+msg+" found");
                     Log.i("tag", "final name is "+temp);

                    priceList.add(temp);

                      Log.i("tag", "price list at count is "+priceList.get(count));
                       Log.i("tag", "count value is "+count);

                       //  alert("count at "+count+" and array is"+final_name_array[count]);
                            temp="";
                       count++;

                            i=j-1;
                            //alert(" name string of i is"+name_string[i]);
                            break;
                        }
                        }


                }

            }



         //******* parsing code for longg

         count=0;

         for(int i=0; i<time_string1.length; i++)
         {



             if(time_string1[i]==':')
             {
                 msg=time_string1[i];
               Log.i("tag", "first time "+msg+" found");
              // alert("first time "+name_string1[i]+" found");

                 for(int j=i+1; j<time_string1.length; j++)
                 {


                    // alert(" in j loop, j at "+name_string[j]);
                     if(time_string1[j]!=':')
                     {
                  // alert("in temp if");
                         temp=temp+time_string1[j];

                         Log.i("tag", "now temp is"+temp);
                     }

                     else if (time_string1[j]==':')
                     {   

                       msg=time_string1[j];
                  Log.i("tag", "else satisfied "+msg+" found");
                  Log.i("tag", "final name is "+temp);

                 timeList.add(temp);

                   Log.i("tag", "time list at count is "+timeList.get(count));
                    Log.i("tag", "count value is "+count);

                    //  alert("count at "+count+" and array is"+final_name_array[count]);
                         temp="";
                    count++;

                         i=j-1;
                         //alert(" name string of i is"+name_string[i]);
                         break;
                     }
                     }


             }

         }

         Log.i("tag", "******************************");

         for(String loop:nameList)
         {
            Log.i("tag", loop);
         }

         for(String loop:priceList)
            {


            Log.i("tag",  loop);
            }   


         for(String loop:timeList)
            {

            Log.i("tag", loop);
            }




    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }



    //ScrollView sv = new ScrollView(this);

    final View linearLayout =  findViewById(R.id.main_layout);
    //LinearLayout layout = (LinearLayout) findViewById(R.id.info);
    ((LinearLayout) linearLayout).setBackgroundResource(R.drawable.bg);
    //sv.addView(linearLayout);    //this is what i have tried
    for(int i=0; i<nameList.size(); i++)
    {
    TextView valueTV = new TextView(this);
    valueTV.setText(":Dish Name: "+nameList.get(i)+" Dish price: "+priceList.get(i)+" Dish time: "+timeList.get(i)+":");
    TextView valueTV1 = new TextView(this);
    valueTV1.setText(":"+nameList.get(i)+":"+priceList.get(i)+":"+timeList.get(i)+":");
    valueTV1.setVisibility(View.GONE);
   // sv.addView(linearLayout);
    chk=new CheckBox(this);
    chk.setId(i);
    chk.setText("Order");
    chk.setTextColor(Color.BLACK);
    Log.i("tag", " i is "+i+" id assigned to chk box is"+chk.getId());

    EditText quantity = new EditText(this);
    quantity.setHint("Quantity");


    valueTV1.setLayoutParams(new LayoutParams(android.app.ActionBar.LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
    ((LinearLayout) linearLayout).addView(valueTV);
    ((LinearLayout) linearLayout).addView(valueTV1);
    ((LinearLayout) linearLayout).addView(chk);
    ((LinearLayout) linearLayout).addView(quantity);

    }
    final EditText specialInstruction = new EditText(this);

    final EditText tableNo = new EditText(this);


    Button myButton = new Button(this);
    TextView tv1 = new TextView(this);
    ((LinearLayout) linearLayout).addView(tv1);
    specialInstruction.setGravity(Gravity.CENTER);
    specialInstruction.setHint("Special Instructions");
    ((LinearLayout) linearLayout).addView(specialInstruction);

    tableNo.setGravity(Gravity.CENTER);
    tableNo.setHint("Table No");
    ((LinearLayout) linearLayout).addView(tableNo);

    myButton.setText("Send Order");


    ((LinearLayout) linearLayout).addView(myButton);



    myButton.setOnClickListener(new OnClickListener() {

        @SuppressLint("ShowToast") @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            boolean oneChecked = false;
             v = null;

             Intent intent = getIntent();
             String quant = null;
             //String username = intent.getExtras().getString("username");
             //Log.i("tag", "username is"+username);
             Log.i("tag", "in Listener");
            for(int i=0; i<=(nameList.size()*4)-1; i++)
            {
                Log.i("tag", "in loop");

                //Log.i("tag", "in loop i is, "+i+" nameList size is "+nameList.size());                    
                    v = ((LinearLayout) linearLayout).getChildAt(i);
                    if (v instanceof CheckBox) {
                        if (((CheckBox) v).isChecked()) {
                            oneChecked = true;

                            if (oneChecked) {
                                Log.i("tag", "in checkbox");
                                Log.i("tag", " check box at "+i+" is checked");

                                 View v1;
                                 v1 = ((LinearLayout) linearLayout).getChildAt(i-1);

                                 View v2;
                                 v2 = ((LinearLayout) linearLayout).getChildAt(i+1);
                                 String quantity="";
                                 if (v1 instanceof TextView)
                                 { 

                                     int id=v1.getId();
                                     Log.i("tag","ids are"+id);
                                    text=((TextView) v1).getText().toString();
                                    Log.i("tag", "in tv if"+text);
                                    if(v2 instanceof EditText){
                                        Log.i("tag", "in et if");
                                        quant=((EditText) v2).getText().toString();
                                         Log.i("tag", "quant is"+quant);
                                         Log.i("tag", "text right now"+text);
                                         quantity= quant+":";
                                    }

                                    text=text+quantity;
                                    Log.i("tag", "values are "+text);

                                    orderList.add(text);
                                 }
                            }

                            oneChecked=false;

                        }
                    }



            }
            Log.i("tag", "final order List is ");
            for(String loop:orderList)
            {
                Log.i("tag", loop);
            }

            String def=orderList.toString();
            String sInst="";
            Log.i("tag", "List is "+def);
            SendOrderAsyncTask runner1 = new SendOrderAsyncTask();

            String inst=specialInstruction.getText().toString();
            Log.i("tag", "inst is "+inst);

            String TableNo =  tableNo.getText().toString();

            if(inst.equals("")){
                Log.i("tag", "inst is null ");
                asyncTaskorder=runner1.execute(def,wname,sInst,TableNo);
            }
            else if(!(inst.equals("")))
            {
                Log.i("tag", "inst does not contain null");
                sInst = specialInstruction.getText().toString();
                Log.i("tag", "in else "+sInst);
                asyncTaskorder=runner1.execute(def,wname,sInst,TableNo);
            }
        Log.i("tag", "spe inst is "+sInst);


           // orderList = null;
            Intent i = new Intent(order.this, order.class);
            startActivity(i);
            finish();
            String asyncResultText = null;
            try {
                asyncResultText = asyncTaskorder.get();
                Log.i("tag", "List in try is "+def);

            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ExecutionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            response = asyncResultText.trim();
            Log.i("tag", "response is "+response); 
            if(response.equals("inservertrue"))
            {
                Log.i("tag", "order sent");
            }


        }
    });



}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.login, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}
}

but the problem is whenever i launch my application it throws me an IllegatStateExceptionthat the child class has already parent. call removeChildfirst.

here is my activity.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:id="@+id/main_layout"
android:layout_height="wrap_content" 
android:orientation="vertical">
</LinearLayout>
like image 508
Muhammad Yawar Avatar asked Jul 14 '16 15:07

Muhammad Yawar


1 Answers

Just do this in your activity.xml file and it will add a ScrollView to your app.

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    tools:context=".MainActivity">
    <LinearLayout
        android:layout_width="wrap_content"
        android:id="@+id/main_layout"
        android:layout_height="wrap_content" 
        android:orientation="vertical">
    </LinearLayout>
</ScrollView>

This should add a ScrollView to your app dynamically when needed, but I haven't gone through your java file, so if any exception occurs there, then I don't know.

like image 87
VatsalSura Avatar answered Sep 28 '22 08:09

VatsalSura