1

I want to dynamic add row in linear layout but i create xml and i run the application crash . my xml and sourcecode below. My Xml Code::

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <LinearLayout
        android:id="@+id/main_lay"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:background="#437654" >

        <Button
            android:id="@+id/all_btn"
            android:layout_width="100dip"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="BACk" />

        <TextView
            android:id="@+id/accepted_all"
            android:layout_width="100dip"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="DownLoad Video" />

        <Button
            android:id="@+id/not_shown"
            android:layout_width="100dip"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="All DOwnload" />
    </LinearLayout>

    <ScrollView
        android:id="@+id/ScrollView01"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >


    </ScrollView>

</LinearLayout>

My custom_row.xml code in Below::

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:descendantFocusability="blocksDescendants"
    android:orientation="horizontal" 
    android:id="@+id/linearchild">

    <ImageView
        android:id="@+id/ColImgPath"
        android:layout_width="50dp"
        android:layout_height="50dp" />

    <TableLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <TableRow
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dip" >

            <TextView
                android:id="@+id/ColStatus"
                android:text="Status"
                android:textAppearance="?android:attr/textAppearanceSmall" />

            <ProgressBar
                android:id="@+id/progressBar"
                style="?android:attr/progressBarStyleHorizontal"
                android:layout_width="100dp"
                android:layout_height="wrap_content" />
        </TableRow>

        <TableRow
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dip" >

            <Button
                android:id="@+id/btnDownload"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Download" />

            <Button
                android:id="@+id/btnView"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Delete" />
        </TableRow>
    </TableLayout>

</LinearLayout>

And My new Edit Sourcecode::

      public class TestDynamicScroll extends Activity {
    ArrayList<Url_Dto> list = new ArrayList<Url_Dto>();
    ScrollView slnLay;
    TableLayout download_table;
    File download;
    public static final int DIALOG_DOWNLOAD_THUMBNAIL_PROGRESS = 0;
    String strDownloaDuRL;
    ArrayList<HashMap<String, Object>> MyArrList = new ArrayList<HashMap<String, Object>>();
    TableRow row, row1, row2;
    ImageView im;
    ProgressBar pr;
    TextView tv;
    Button dl;
    Button cl;
    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_dynamic_scroll);

        list = DBAdapter.getUrl_Detail();
        fillCountryTable();
    }

    void fillCountryTable() {
         mContext =TestDynamicScroll.this;
        LinearLayout childln = null ;

        slnLay = (ScrollView) findViewById(R.id.scrollView1);
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View convertView = inflater.inflate(R.layout.custom_row, null);


        for (int current = 0; current < list.size(); current++) {

            Log.v("log_tag", "Current ::: " + current);
            childln = (LinearLayout) convertView.findViewById(R.id.linearchild);
            im = new ImageView(this);
            im = (ImageView) convertView.findViewById(R.id.ColImgPath);
            im.setImageResource(Url_Dto.images[current]);

            childln.addView(im);

            tv = new TextView(this);
            tv = (TextView) convertView.findViewById(R.id.ColStatus);
            tv.setText("...");

            childln.addView(tv);

            pr = new ProgressBar(this);
            pr = (ProgressBar) convertView.findViewById(R.id.progressBar);

            childln.addView(pr);

            dl = new Button(this);
            dl = (Button) convertView.findViewById(R.id.btnDownload);

            childln.addView(dl);

            cl = new Button(this);
            cl = (Button) convertView.findViewById(R.id.btnView);


            childln.addView(cl);


            dl.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    dl.setEnabled(false);
                    dl.setTextColor(Color.GRAY);

                    //startDownload(dl.getId());
                }
            });

        }
        slnLay.addView(childln);




    }

    public void startDownload(final int position) {

        Runnable runnable = new Runnable() {
            int Status = 0;

            public void run() {

                // String urlDownload = list.get(position).url_video;
                String urlDownload = list.get(position).url_video;
                Log.v("log_tag", "urlDownload   ::: " + urlDownload);

                int count = 0;
                try {

                    URL url = new URL(urlDownload);
                    URLConnection conexion = url.openConnection();
                    conexion.connect();

                    int lenghtOfFile = conexion.getContentLength();
                    Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

                    InputStream input = new BufferedInputStream(
                            url.openStream());

                    // Get File Name from URL
                    String fileName = urlDownload.substring(
                            urlDownload.lastIndexOf('/') + 1,
                            urlDownload.length());
                    download = new File(
                            Environment.getExternalStorageDirectory()
                                    + "/download/");
                    if (!download.exists()) {
                        download.mkdir();
                    }
                    strDownloaDuRL = download + "/" + fileName;
                    OutputStream output = new FileOutputStream(strDownloaDuRL);

                    byte data[] = new byte[1024];
                    long total = 0;

                    while ((count = input.read(data)) != -1) {
                        total += count;
                        Status = (int) ((total * 100) / lenghtOfFile);
                        output.write(data, 0, count);



                        TestDynamicScroll.this.runOnUiThread(new Runnable() {
                            public void run() {
                                // updateStatus(position, Status);

                            }
                        });

                    }

                    output.flush();
                    output.close();
                    input.close();

                } catch (Exception e) {
                }

            }
        };
        new Thread(runnable).start();
    }

}

MY DbAdpter Class In Below:::

public class DBAdapter {
    public static String url = "http://imprintingdesign.com/hiren_testing/TestHopeNew/testHope/data/url.json";


    public static ArrayList<Url_Dto> getUrl_Detail() {

        ArrayList<Url_Dto> fetchUrl_Detail = new ArrayList<Url_Dto>();
        String result = "";
        InputStream is = null;

        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

        // http post
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }
        // convert response to string
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }

        // parse json data
        try {
            JSONObject json_obj = new JSONObject(result);
            JSONArray j_Arr_fn = json_obj.getJSONArray("children");

            for (int i = 0; i < j_Arr_fn.length(); i++) {
                JSONObject json_objs = j_Arr_fn.getJSONObject(i);
                Url_Dto proDto = new Url_Dto();
                proDto.url_video= json_objs.getString("videoUrl");
                Log.v("log_tag","Url  :::"+ json_objs.getString("videoUrl"));
                fetchUrl_Detail.add(proDto);
                }

        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }
        return fetchUrl_Detail;

    }

I want to like layout display in below:

enter image description here

My error Get It:::

 03-14 13:31:39.453: E/AndroidRuntime(770): FATAL EXCEPTION: main
03-14 13:31:39.453: E/AndroidRuntime(770): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.testdyanamicscroll/com.example.testdyanamicscroll.TestDynamicScroll}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
03-14 13:31:39.453: E/AndroidRuntime(770):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
03-14 13:31:39.453: E/AndroidRuntime(770):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
03-14 13:31:39.453: E/AndroidRuntime(770):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
03-14 13:31:39.453: E/AndroidRuntime(770):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
03-14 13:31:39.453: E/AndroidRuntime(770):  at android.os.Handler.dispatchMessage(Handler.java:99)
03-14 13:31:39.453: E/AndroidRuntime(770):  at android.os.Looper.loop(Looper.java:130)
03-14 13:31:39.453: E/AndroidRuntime(770):  at android.app.ActivityThread.main(ActivityThread.java:3683)
03-14 13:31:39.453: E/AndroidRuntime(770):  at java.lang.reflect.Method.invokeNative(Native Method)
03-14 13:31:39.453: E/AndroidRuntime(770):  at java.lang.reflect.Method.invoke(Method.java:507)
03-14 13:31:39.453: E/AndroidRuntime(770):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
03-14 13:31:39.453: E/AndroidRuntime(770):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
03-14 13:31:39.453: E/AndroidRuntime(770):  at dalvik.system.NativeStart.main(Native Method)
03-14 13:31:39.453: E/AndroidRuntime(770): Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
03-14 13:31:39.453: E/AndroidRuntime(770):  at android.view.ViewGroup.addViewInner(ViewGroup.java:1976)
03-14 13:31:39.453: E/AndroidRuntime(770):  at android.view.ViewGroup.addView(ViewGroup.java:1871)
03-14 13:31:39.453: E/AndroidRuntime(770):  at android.view.ViewGroup.addView(ViewGroup.java:1828)
03-14 13:31:39.453: E/AndroidRuntime(770):  at android.view.ViewGroup.addView(ViewGroup.java:1808)
03-14 13:31:39.453: E/AndroidRuntime(770):  at com.example.testdyanamicscroll.TestDynamicScroll.fillCountryTable(TestDynamicScroll.java:76)
03-14 13:31:39.453: E/AndroidRuntime(770):  at com.example.testdyanamicscroll.TestDynamicScroll.onCreate(TestDynamicScroll.java:55)
03-14 13:31:39.453: E/AndroidRuntime(770):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-14 13:31:39.453: E/AndroidRuntime(770):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
03-14 13:31:39.453: E/AndroidRuntime(770):  ... 11 more
2
  • DbAdpter in my json File I get Url From jshon. Commented Mar 12, 2013 at 12:34
  • Hi Droider I put my DBadpter Code Please see it. Commented Mar 12, 2013 at 12:35

2 Answers 2

1

you need to use object of LinearLayout.LayoutParam when adding the LayoutParam to child view of LinearLayout..

Change the following code

for(int i=0;i<list.size();i++){

             im[i] = new ImageView(TestDynamicScroll.this);

            im[i].setLayoutParams(new LayoutParams(50, 50));

            im[i].setImageResource(list.get(i).images[i]);
            slnLay.addView(im[i]);

        }

with

for(int i=0;i<list.size();i++){

         im[i] = new ImageView(TestDynamicScroll.this);

        im[i].setLayoutParams(new LinearLayout.LayoutParams(50, 50));

        im[i].setImageResource(list.get(i).images[i]);
        slnLay.addView(im[i]);

    }
Sign up to request clarification or add additional context in comments.

5 Comments

Hi praful Thanks for reply but i want like i put image in row all items and i put your code imageview not display in my view please check in my xml code what wrong in my code please help me!!!
no any error get but not display in image view in activity.only see the top linear layout show.
can you post the screen shot of the current screen?
thanks praful completly working but how to set progressbar and button add in per row dynamic add please help me.
check out the answer from @Aashish ... you need to use similar approach... and if you have many item in the list then it would make sense to use ListView to create the view...
0

Sorry I posted the earlier answer little too quick what you need is to create a seperate xml file for a row you want and then inflate that view and add dynamically to your layout

like this

 private LinearLayout mInputView;
  mInputView = (LinearLayout) getLayoutInflater().inflate(R.layout.row_xml, null);
  ImageView newImage=(ImageView)mInputView.findViewbyId(R.id.imageid);

and add this inflated layout to your linearlayout.

the row_xml file may have structure like this

<LinearLayout>
<ImageView/>
<ProgressBar/>
<ImageView/>

</LinearLayout>

2 Comments

Ashish i want to dynamic add image view and progressbar and button .and add scrollview in linearlayout and i not used listview only scrollview .how to add it.
create a xml view for the row just like you do with listview and then inflate it to linearlayout you can use the code I posted for that. and just add this created layout to your own linearlayout you can modify it just like you modify listview row in the getView method

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.