Android TableLayout

tomier

Aktives Mitglied
Liebe Leute,

Ich kämpfe mit dem TableLayout in Android ein wenig.

Ich will ein Layout mit 4 Komponenten pro Zeile:

EditText (Uhrzeit) Spinner(dynamisch befüllt) EditText (nur Integer) Spinner(dynamisch befüllt) Button (zum Löschen der Zeile)

Anmerkung: das Uhrzeitfeld ist noch nicht im Quellcode

Der Minus-Button wird mir gar nicht angezeigt.
Das EditText Feld (nur Integer) wird zu klein angezeigt und setEms() oder setWidth() hat beides keine Veränderung.

Dann hätte ich eine Änderung frage:
Wie kann ich wenn ich im 1. Spinner etwas auswähle (auf onSelectItemListener()) den anderen Spinner-Inhalt ändern? Ich habe eine andere List<String> je nach dem was ich auswähle und will den Spinner-Inhalt des 2. Spinners dann neu befüllen.
Die Liste befüllt er mir natürlich aber wie kann ich das im Layout sichtbar ändern?

Mein zusätzliches Problem beim Löschen ist folgendes:
Ich weise den einzelnen Elementen, welche ich am Ende auslesen will, eine ID zusammengesetzt aus dem Rowcount und einer Zahl (3000 für EditText, 1000 für den 1.Spinner, usw.) zu.

Jedoch wenn ich lösche müsste ich ja den rowcount verringern, jedoch ist dann beim iterieren ein Fehler. habt ihr da eine Idee?



[XML]- <LinearLayout 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" android😱rientation="vertical">
- <ScrollView android:id="@+id/scrollView1" android:layout_width="match_parent" android:layout_height="wrap_content">
- <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android😱rientation="vertical">
- <TableLayout android:id="@+id/tableLayout1" android:layout_width="match_parent" android:layout_height="wrap_content">
- <TableRow android:id="@+id/tableRow1" android:layout_width="wrap_content" android:layout_height="wrap_content">
- <EditText android:id="@+id/editText1" android:layout_width="30dp" android:layout_height="wrap_content" android:ems="10" android:inputType="numberSigned">
<requestFocus />
</EditText>
<Spinner android:id="@+id/spinner1" android:layout_width="match_parent" android:layout_height="wrap_content" android😛rompt="@string/product_prompt" />
</TableRow>
</TableLayout>
- <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content">
<Button android:id="@+id/btnBerechnen" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button_berechnen" />
<Button android:id="@+id/btnAdd" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button_add" />
</LinearLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>[/XML]

Java:
package at.gemuesebauauer.ernterechner;


import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.Toast;

@SuppressLint({ "ParserError", "ParserError", "ParserError", "ParserError" }) public class MainActivity extends Activity {


	private TableLayout tabLay;

	private List<Integer> amount= new ArrayList<Integer>();
	private List<String> productsforspinner= new ArrayList<String>();
	private List<String> client= new ArrayList<String>();
	private List<String> manufacture= new ArrayList<String>();
	private File clients;
	private File filemanufactures;
	private TextFileEdit TextFileEdit = new TextFileEdit();
	
	private int numberofrows;
	
	
	@Override
	  public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.activity_main);
	    numberofrows=0;
	    
	    clients=new File (MainActivity.this.getFilesDir().getPath().toString() + "/kunden.txt");
	    filemanufactures= new File (MainActivity.this.getFilesDir().getPath().toString() + "/erzeugnisse.txt");
		 
	    TextFileEdit.writeToSDCard(clients, "Herzog");
	    TextFileEdit.writeToSDCard(clients, "Marksteiner");
	    TextFileEdit.writeToSDCard(clients, "LGV");
	    
	    try {
			client=TextFileEdit.loadTextFile(clients);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	    Kunde kunde1= new Kunde (client.get(0), MainActivity.this);
	    List<Produkt> tmp_clientproduktliste =TextFileEdit.getProduktliste(kunde1.getFile(), filemanufactures);
		for(int i=0;i<tmp_clientproduktliste.size();i++){
			productsforspinner.add(tmp_clientproduktliste.get(i).getProduktname());
		}

		createRowsMain(5); 
		
		TextFileEdit.writeToSDCard(filemanufactures,"01 Brokkoli PH");
	    TextFileEdit.writeToSDCard(filemanufactures,"02 Brokkoli PK");
	    TextFileEdit.writeToSDCard(filemanufactures,"03 Salat PH");
	 
	    TextFileEdit.writeToSDCard(kunde1.getFile(),"Produkt 1");
	    TextFileEdit.writeToSDCard(kunde1.getFile(),"030201030301");
	    TextFileEdit.writeToSDCard(kunde1.getFile(),"Produkt 2");
	    TextFileEdit.writeToSDCard(kunde1.getFile(),"040310020501");
	    TextFileEdit.writeToSDCard(kunde1.getFile(),"Produkt 3");
	    TextFileEdit.writeToSDCard(kunde1.getFile(),"05031002");
	    TextFileEdit.writeToSDCard(kunde1.getFile(),"Produkt 4");
	    TextFileEdit.writeToSDCard(kunde1.getFile(),"1003");
	    
	    tabLay = (TableLayout)findViewById(R.id.tableLayout1);
	    tabLay.removeAllViews();
        //createRow();
	    Button buBerechnen = (Button)findViewById(R.id.btnBerechnen);
	    Button buAdd = (Button)findViewById(R.id.btnAdd);
	    
	    
	    
	    
	    buBerechnen.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	Bestellliste ernteliste= new Bestellliste("Bestellliste 1");
            	String product="";
            	int amounte=0;
            	for (int y=1;y<=numberofrows;y++) {
            		EditText text = (EditText) findViewById(y+3000);
                	Spinner sp_product = (Spinner) findViewById(y+1000);
                	Spinner sp_client = (Spinner) findViewById(y+2000);
                	
                	if (text.getText().toString().equals("")) {
                		amounte=0;
                	}
                	else {
                		amounte=Integer.valueOf(text.getText().toString());
                	}
                	product=sp_product.getSelectedItem().toString();
                	String clientname=sp_client.getSelectedItem().toString();
                	ernteliste.addClientToBestellliste(clientname);
                	
                	ernteliste.getBestelllistepositionen().
                	get(clientname).addlistManufactures(product, amounte);
                	
              }
            	
            	for(HashMap.Entry<String, Bestelllisteposition> e : ernteliste.getBestelllistepositionen().entrySet()){
          		  String s = e.getKey();
          		  Bestelllisteposition d = e.getValue();
          		
          		  String product1="";
          		  String outtext="";
          		  int amount2=0;
	          		  for(HashMap.Entry<String, Integer> f : ernteliste.getBestelllistepositionen().get(s).getlistManufactures().entrySet()){
	          			  product1 = f.getKey();
	          			  amount2 = f.getValue();
	          			  
	          			  outtext=outtext+"Artikel "+ product1 +" BINDE Menge "+amount2+"\n";
	              		  
	          		  }
	          		  Toast.makeText(MainActivity.this, 
	                  			"Kunde "+ d.getClient() + "\n"+
	                  			outtext
	
	                  			            				, Toast.LENGTH_LONG).show();
            		} //end of for ernteliste
            	}	//end of for erntelistenposition
        });
	    
	    buAdd.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	createRowsMain(1);
              }
        });
	   
	    
	    
	} // end of onCreate
	

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.activity_main, menu);
        return true;
    }
 
    public Spinner newSpinner(List<String> list) {
        final Spinner sp1= new Spinner(MainActivity.this);
    ArrayAdapter<String> adp1=new ArrayAdapter<String>(MainActivity.this,
                        android.R.layout.simple_spinner_item,list);
        adp1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sp1.setAdapter(adp1);

    sp1.setOnItemSelectedListener(new OnItemSelectedListener()
            {
              public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long id) {
                   // TODO Auto-generated method stub
            	  
            	//  Toast.makeText(getBaseContext(),list.get(position), Toast.LENGTH_SHORT).show();
            	  	 }
               public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
            }
               });
    	return sp1;
    } // enf of newSpinner()
    @Override
    protected void onActivityResult(int requestCode,
                                     int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == 100){
        	data.getExtras().get("");
        }
 
    }
    public void createRowsMain(int rowcount){
    	for (int i=0; i<rowcount;i++) {
    		numberofrows++;
    		TableRow tr;
        	EditText editText;
        	Spinner sp_product;
        	Spinner sp_client;
        	Button minus;
        	sp_product = newSpinner(productsforspinner);
        	
        	sp_product.setOnItemSelectedListener(new OnItemSelectedListener()
            {
              public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long id) {
                   // TODO Auto-generated method stub
            	  
            	  
            	  Kunde kunde_tmp= new Kunde (arg0.getItemAtPosition(position).toString(), MainActivity.this);
          	    List<Produkt> tmp_clientproduktliste =TextFileEdit.getProduktliste(kunde_tmp.getFile(), filemanufactures);
          		for(int i=0;i<tmp_clientproduktliste.size();i++){
          			productsforspinner.add(tmp_clientproduktliste.get(i).getProduktname());
          		
          		}
            	  
            	  /*
            	  if(arg0.getItemAtPosition(position).toString().contains("MIXXX")){
            		  Intent i = new Intent(getApplicationContext(), Mix_Salat_Activity.class);
                	  i.putExtra("selected_item", arg0.getItemAtPosition(position).toString());
                	  startActivityForResult(i, 100); 
            	  }*/
            	  
            	  	 }
               public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
            }
               });
        	
        	minus = new Button(MainActivity.this);
        	sp_product.setId(numberofrows+1000);
        	sp_client = newSpinner(client);   
        	sp_client.setId(numberofrows+2000);
        	editText = new EditText(MainActivity.this);
            /* Create a new row to be added. */
            
            editText.setId(numberofrows+3000);
            //editText.setWidth(25);
            editText.setEms(65);
            //editText.setHeight(20);
            editText.setInputType(InputType.TYPE_CLASS_NUMBER); 
            
            minus.setId(numberofrows+4000);
            minus.setText("-");
            minus.setLayoutParams(new LayoutParams(
                    LayoutParams.MATCH_PARENT,
                    LayoutParams.WRAP_CONTENT));
            minus.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                //	final TableRow tr1=tr;
                //	tabLay.removeView(tr1);
                	tabLay.removeViewAt(numberofrows);
                  }
            });
            tr = new TableRow(MainActivity.this);
            
            tr.addView(sp_client);
            tr.addView(editText);
            tr.addView(sp_product);
            
            tr.addView(minus);
            
            
            tr.setLayoutParams(new LayoutParams(
                    LayoutParams.MATCH_PARENT,
                    LayoutParams.WRAP_CONTENT));
            tr.setId(numberofrows+5000);
            tabLay.addView(tr,new TableLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    	}
    }
    
    
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menuitem1: 
            	setContentView(R.layout.activity_main);
            	Toast.makeText(this, "You pressed the icon!", Toast.LENGTH_LONG).show();
            break;
            case R.id.menuitem2: 
            	Intent newProductActivity = new Intent(getApplicationContext(), NewProductActivity.class);
            	 /*
                //Sending data to another Activity
                nextScreen.putExtra("name", inputName.getText().toString());
                nextScreen.putExtra("email", inputEmail.getText().toString());
 
                Log.e("n", inputName.getText()+"."+ inputEmail.getText());
            	  	*/
            	
                startActivity(newProductActivity);
            	Toast.makeText(this, "Neues Produkt!", Toast.LENGTH_LONG).show();
            break;
            case R.id.menuitem3: 
            	setContentView(R.layout.new_client);
            	Toast.makeText(this, "You pressed the icon and text!", Toast.LENGTH_LONG).show();
            break;
            case R.id.menuitem4: 
            	setContentView(R.layout.activity_main);
            	Toast.makeText(this, "You pressed the icon and text!", Toast.LENGTH_LONG).show();
            break;
                             
        }
        return true;
    }
   /*
    public void printTheDoc() {
       
    try {
	    // Open the image file
	    InputStream is = new BufferedInputStream(
	        new FileInputStream("filename.gif"));
	    // Create the print job
	    DocPrintJob job = service.createPrintJob();
	    Doc doc = new SimpleDoc(is, flavor, null);

	    // Monitor print job events
	    PrintJobWatcher pjDone = new PrintJobWatcher(job);

	    // Print it
	    job.print(doc, null);

	    // Wait for the print job to be done
	    pjDone.waitForDone();

	    // It is now safe to close the input stream
	    is.close();
	} catch (PrintException e) {
	} catch (IOException e) {
	}
        }*/

    
    
    
}
 
So ich komme nicht wirklich weiter. Und mir ist jetzt noch ein Problem aufgefallen:

Ich will ja wenn in einem "client"-Spinner einen Eintrag auswählt sich der zugehörige "product"-Spinner (=der Spinner in der gleichen Zeile)
dazu anpasst.

Das Problem ist wenn ich in einem "client" -Spinner einen Eintrag auswähle zeigen ALLE (=alle bestehenden Zeilen) "product"-Spinner aufeinmal die Einträge für den aktuellen "client" -Spinner-Eintrag an.

Aber ich will ja nur immer pro Zeile die Anpassung. Bin schon echt verzweifelt. Nach 2 Tagen 10 Stunden herumspielen komm ich nicht mehr drauf.

Zwei Klassen habe ich vergessen zu posten ohne die wird das Komplieren schwierig.

Hier ist nochmal die Klasse "MainActivity.java". Ich habe Sie etwas umgeschrieben und umgearbeitet.

Java:
package at.gemuesebauauer.ernterechner;


import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.Toast;

@SuppressLint({ "ParserError", "ParserError", "ParserError", "ParserError" }) public class MainActivity extends Activity {


	private TableLayout tabLay;
	private LinearLayout tabLayRow;

	private List<Integer> amount= new ArrayList<Integer>();
	private List<List<String>> productsforspinner= new ArrayList<List<String>>();
	private List<String> tmp_for_productsforspinner= new ArrayList<String>();
	private List<Kunde> client= new ArrayList<Kunde>();
	private List<String> manufacture= new ArrayList<String>();
	private File clients;
	private File producte;
	private File filemanufactures;
	private TextFileEdit TextFileEdit = new TextFileEdit();
	private List<String> client_fill_lift= new ArrayList<String>();
	private List<Spinner> sp_product = new ArrayList<Spinner>();
	private List<Spinner> sp_client = new ArrayList<Spinner>();
	private List<ArrayAdapter<String>> adp_sp_product = new ArrayList<ArrayAdapter<String>>();
	private List<ArrayAdapter<String>> adp_sp_client= new ArrayList<ArrayAdapter<String>>();
	private Button minus;
	private int numberofrows;
	private int row_id;
	
	private View row;
	@Override
	  public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    
	    //Layout auf activity_main.xml setzen
	    setContentView(R.layout.activity_main);
	    
	    numberofrows=0;
	    row_id=0;
	    // Pfaddefinition der Files
	    clients=new File (MainActivity.this.getFilesDir().getPath().toString() + "/kunden5.txt");
	    filemanufactures= new File (MainActivity.this.getFilesDir().getPath().toString() + "/erzeugnisse.txt");
		
	    // Nur für Test zwecke
	    //producte = new File (MainActivity.this.getFilesDir().getPath().toString() + "/producte1.txt");
	    
		// clients - File beschreiben
	    
	    TextFileEdit.writeToSDCard(clients, "Markes");
	    TextFileEdit.writeToSDCard(clients, "LGV");
	    TextFileEdit.writeToSDCard(clients, "HerzogAB");
	    
	    // erzeugnisse bzw. manufactures - file beschreiben
	    TextFileEdit.writeToSDCard(filemanufactures,"01 Brokkoli PH");
	    TextFileEdit.writeToSDCard(filemanufactures,"02 Brokkoli PK");
	    TextFileEdit.writeToSDCard(filemanufactures,"03 Salat PH");
	    
	    // Client List<Kunde> erstellen
	    client.clear();
	    try {
	    	
	    	client_fill_lift=TextFileEdit.loadTextFile(clients);
	    	for (int i=0; i<client_fill_lift.size();i++)
	    	client.add(new Kunde(client_fill_lift.get(i), MainActivity.this));
		//	}
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	    
	    // Beschreibe die Produktfiles der einzelnen Kunden 
	    
	    Kunde kunde1= client.get(0);
	    TextFileEdit.writeToSDCard(kunde1.getFile(),"Mix Salat Rk167 6 Stk");
	    TextFileEdit.writeToSDCard(kunde1.getFile(),"030201030303");
	    TextFileEdit.writeToSDCard(kunde1.getFile(),"Mix Salat PH 9 Stk");
	    TextFileEdit.writeToSDCard(kunde1.getFile(),"040310020503");
	    TextFileEdit.writeToSDCard(kunde1.getFile(),"Produkt 3");
	    TextFileEdit.writeToSDCard(kunde1.getFile(),"05031003");
	    TextFileEdit.writeToSDCard(kunde1.getFile(),"Produkt 6");
	    TextFileEdit.writeToSDCard(kunde1.getFile(),"1003");
	    Kunde kunde2= client.get(1);

	    TextFileEdit.writeToSDCard(kunde2.getFile(),"Produkt 7");
	    TextFileEdit.writeToSDCard(kunde2.getFile(),"050210019003");
	    
	    Kunde kunde4= client.get(3);
	    TextFileEdit.writeToSDCard(kunde4.getFile(),"Produkt A");
	    TextFileEdit.writeToSDCard(kunde4.getFile(),"030201030301");
	    TextFileEdit.writeToSDCard(kunde4.getFile(),"Produkt B");
	    TextFileEdit.writeToSDCard(kunde4.getFile(),"040310020501");
	    
	 
	    
	    // Erstelle neue List<Produkt> aus dem Kundenfile für die Startanzeige der Spinners
	    List<Produkt> tmp_clientproduktliste =TextFileEdit.getProduktliste(kunde4.getFile(), filemanufactures);
	    
	    for(int i=0;i<tmp_clientproduktliste.size();i++){
	    	tmp_for_productsforspinner.add(tmp_clientproduktliste.get(i).getProduktname());
			
		}
	    // Befülle  List<List<String>> productsforspinner mit den String-Listen für die einzelnen Spinner 
	    productsforspinner.add(tmp_for_productsforspinner);

	    // Holt die XML-Komponenten
	    tabLay = (TableLayout)findViewById(R.id.tableLayout1);
	    tabLay.removeAllViews();
        //createRow();
	    Button buBerechnen = (Button)findViewById(R.id.btnBerechnen);
	    Button buAdd = (Button)findViewById(R.id.btnAdd);
	    
	    buAdd.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	// Erstellt eine neue Tabelle-Zeile mit allen Elementen
            	createRowsMain(1);
              }
        });
	   
	    createRowsMain(1);	    
	} // end of onCreate
	

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.activity_main, menu);
        return true;
    }
 
    public void newSpinner(List<String> list, int type) {
    	//Typ 0 = for products spinner; Typ 1 = for client spinner
    	// Erzeugt neuen Spinner mit Typ 1 
        if (type==1){
        	sp_client.add(new Spinner(MainActivity.this));
        	adp_sp_client.add(new ArrayAdapter<String>(MainActivity.this,
                    android.R.layout.simple_spinner_item,list));
        	adp_sp_client.get(numberofrows-1).setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        	sp_client.get(numberofrows-1).setAdapter(adp_sp_client.get(numberofrows-1));
        	
        }
        //Typ 0 = for products spinner; Typ 1 = for client spinner
        if (type==0){
        	sp_product.add(new Spinner(MainActivity.this));
        	adp_sp_product.add(new ArrayAdapter<String>(MainActivity.this,
                    android.R.layout.simple_spinner_item,list));
        	adp_sp_product.get(numberofrows-1).setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        	sp_product.get(numberofrows-1).setAdapter(adp_sp_product.get(numberofrows-1));
        }
    
    	
    } // end of newSpinner()
    @Override
    protected void onActivityResult(int requestCode,
                                     int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == 100){
        	data.getExtras().get("");
        }
 
    }
    
    
    public void createRowsMain(int rowcount){
    	for (int i=0; i<rowcount;i++) {
    		numberofrows++;
    		TableRow tr;
        	EditText editText;
        	
        	newSpinner(client_fill_lift, 1);
        	newSpinner(productsforspinner.get(row_id), 0);
        	
        	minus = new Button(MainActivity.this);
        	sp_product.get(rowcount-1).setId(numberofrows+1000);
        	   
        	sp_client.get(rowcount-1).setId(numberofrows+2000);
        	
        	
        	editText = new EditText(MainActivity.this);
            /* Create a new row to be added. */
            
            editText.setId(numberofrows+3000);
            //editText.setWidth(25);
            editText.setEms(65);
            //editText.setHeight(20);
            editText.setInputType(InputType.TYPE_CLASS_NUMBER); 
            
            minus.setId(numberofrows+4000);
            minus.setText("-");
            minus.setLayoutParams(new LayoutParams(
                    LayoutParams.MATCH_PARENT,
                    LayoutParams.WRAP_CONTENT));
            minus.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                //	final TableRow tr1=tr;
                //	tabLay.removeView(tr1);
                	tabLay.removeViewAt(numberofrows);
                  }
            });
            
            tr = new TableRow(MainActivity.this);
            
            tr.setLayoutParams(new LayoutParams(
                    LayoutParams.MATCH_PARENT,
                    LayoutParams.WRAP_CONTENT));
            tr.setId(numberofrows+5000);
            tr.setTag(numberofrows);
            
            
            tr.addView(sp_client.get(numberofrows-1));
            //  tr.addView(editText);
              tr.addView(sp_product.get(numberofrows-1));
              
              tr.addView(minus);
            row=tr;
            tabLay.addView(row,new TableLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
            
            sp_client.get(numberofrows-1).setOnItemSelectedListener(new OnItemSelectedListener(){

				public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long id) {
					// TODO Auto-generated method stub
					row_id=tabLay.indexOfChild(row);
					
					Toast.makeText(MainActivity.this,String.valueOf("clientsize"+client.size()), Toast.LENGTH_LONG).show();
	                
	        	    for(int i=0;i<client.size();i++) {
	        	    	if (arg0.getItemAtPosition(position).toString().equals(client.get(i).getClientname())) {
	        	    		
	    	            	List<Produkt> tmp_clientproduktliste =TextFileEdit.getProduktliste(client.get(i).getFile(), filemanufactures);
	    	            	
	    	            	tmp_for_productsforspinner.clear();
	    	        	    for(int y=0;y<tmp_clientproduktliste.size();y++){
	    	        	    	tmp_for_productsforspinner.add(tmp_clientproduktliste.get(y).getProduktname());
	    	        	    	// Ist ein testoutput
	    	        	    	// Toast.makeText(MainActivity.this,String.valueOf(tmp_clientproduktliste.get(i).getProduktname()), Toast.LENGTH_LONG).show();
	    	  	        	   
	    	        		}
	    	        	    productsforspinner.add(tmp_for_productsforspinner);
		        	    	//ArrayAdapter<String> adp_sp_product_tmp=new ArrayAdapter<String>(MainActivity.this,
			                  //      android.R.layout.simple_spinner_item,tmp_for_productsforspinner);
			        	  //  sp_product.get(Integer.valueOf(row.getTag().toString())-1).setAdapter(adp_sp_product_tmp);
			        	    
			        	 //   adp_sp_product.get(Integer.valueOf(row.getTag().toString())-1).notifyDataSetChanged();	
			            		break;
		        	    }
	        	    }
	        	    
				}

				public void onNothingSelected(AdapterView<?> arg0) {
					// TODO Auto-generated method stub
					
					
				}
    	    }); //end of onselectitemlistener
        	

                        /*
            row.setOnClickListener(new OnClickListener(){

    	        public void onClick(View v){
    	            // TODO Auto-generated method stub
    	            row_id=tabLay.indexOfChild(row);
    	            Toast.makeText(MainActivity.this, 
    	          			"clickedrow "+row_id

    	          			            				, Toast.LENGTH_LONG).show();
    	        }
    	    });*/
           
    	}
    }
    
    
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menuitem1: 
            	setContentView(R.layout.activity_main);
            	Toast.makeText(this, "You pressed the icon!", Toast.LENGTH_LONG).show();
            break;
            case R.id.menuitem2: 
            	/*Intent newProductActivity = new Intent(getApplicationContext(), NewProductActivity.class);
            	 
                //Sending data to another Activity
                nextScreen.putExtra("name", inputName.getText().toString());
                nextScreen.putExtra("email", inputEmail.getText().toString());
 
                Log.e("n", inputName.getText()+"."+ inputEmail.getText());
            	  	
            	
                startActivity(newProductActivity);*/
            	Toast.makeText(this, "Neues Produkt!", Toast.LENGTH_LONG).show();
            break;
            case R.id.menuitem3: 
            	setContentView(R.layout.new_client);
            	Toast.makeText(this, "You pressed the icon and text!", Toast.LENGTH_LONG).show();
            break;
            case R.id.menuitem4: 
            	setContentView(R.layout.activity_main);
            	Toast.makeText(this, "You pressed the icon and text!", Toast.LENGTH_LONG).show();
            break;
                             
        }
        return true;
    }
}

Klasse Kunde.java
Java:
package at.gemuesebauauer.ernterechner;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.content.Context;

public class Kunde extends Activity {
	private String clientname;
	private File kundenproduktfile;
	private Map<Produkt, Integer> Bestellliste= new HashMap<Produkt, Integer>();
	private TextFileEdit TextFileEdit = new TextFileEdit(); 
	public Kunde (String clientname, Context context) {
		this.clientname=clientname;
		this.kundenproduktfile=new File(context.getFilesDir().getPath().toString() + "/"+clientname+"_produkte.txt");
	}
	
	public String getClientname() {
		 return clientname;
	}	//end getClientname
	
	public File getFile() {
		 return kundenproduktfile;
	}	//end getFile
	
	public Map<Produkt, Integer> getBestellliste() {
		 return Bestellliste;
	}	//end getBestellliste

	public void writeToProductfile(String text) {
		TextFileEdit.writeToSDCard(kundenproduktfile, text);
	}	//end writeToProductfile
	
	public void addBestellliste(Produkt produkt,int amount){
		if(!Bestellliste.containsKey(produkt)) {
			int tmp=Bestellliste.get(produkt);
			tmp=tmp+amount;
			Bestellliste.put(produkt, tmp);
		}
		else {
			Bestellliste.put(produkt, amount);
		}	
	}	//end addBestellliste
}

Klasse TextFileEdit
Java:
package at.gemuesebauauer.ernterechner;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TextFileEdit {
	
public List<String> loadTextFile(File file) throws IOException {
	
	List<String> listtmp= new ArrayList<String>();
	try{
		  // Open the file that is the first 
		  // command line parameter
		  FileInputStream fstream = new FileInputStream(file);
		  // Get the object of DataInputStream
		  DataInputStream in = new DataInputStream(fstream);
		  BufferedReader br = new BufferedReader(new InputStreamReader(in));
		  String strLine;
		  //Read File Line By Line
		  while ((strLine = br.readLine()) != null)   {
		  // Print the content on the console
			  listtmp.add(strLine);
		  }
		  //Close the input stream
		  in.close();
		  return listtmp;
		    }catch (Exception e){//Catch exception if any
		  System.err.println("Error: " + e.getMessage());
		  return null;
		  }
}
	
public void writeProductFile (File file) {
	writeToSDCard(file,"Produkt 1");
    writeToSDCard(file,"030201030301");
    writeToSDCard(file,"Produkt 2");
    writeToSDCard(file,"040310020501");
    writeToSDCard(file,"Produkt 3");
    writeToSDCard(file,"05031002");
    writeToSDCard(file,"Produkt 4");
    writeToSDCard(file,"1003");
}
public String writeToSDCard(File file, String text) {
	
	String content = text;
	boolean exists=false;
	
	// if file doesnt exists, then create it
	if (!file.exists()) {
		try {
			file.createNewFile();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	try {
		List<String> textfileread=loadTextFile(file);
		for (int i=0;i<textfileread.size();i++) {
			if (text.equals(textfileread.get(i))) {
				exists=true;
				return "Eintrag existiert bereits!";
			}
			else {
				exists=false;
			}
		}
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		return "Fehler bei Dateierstellung";
	}
	if (exists==false) {
		FileWriter fw = null;
		
		try
		{
			fw = new FileWriter(file,true);
			BufferedWriter bufferWritter = new BufferedWriter(fw);
	        
	        bufferWritter.append(content);
	        bufferWritter.newLine();
	        bufferWritter.close();
	        
		}
		catch ( IOException f ) {
			
			System.out.println( "Konnte Datei nicht erstellen" );
			return "Konnte Datei nicht erstellen";
		}
		finally {
			try {
				if ( fw != null ) fw.close();
				return "Datei "+file+"wurde erstellt bzw. schrieben";
				} catch (IOException f) {}
				
			}
	}
	return "Datei "+file+" ordnungsgemäß erstellt.";
	 
}

public List<Produkt> getProduktliste(File produktfile, File manufactures){
	 List<Produkt> produktListe = new ArrayList<Produkt>();
	 try {
       	
       	
       	// Create Produkt Liste
			List<String> produktelines =loadTextFile(produktfile);
			List<String> erzeugnisse =loadTextFile(manufactures);
			Map<Integer, String> mapManufactures= new HashMap<Integer, String>();
			for(int i=0;i<erzeugnisse.size();i++) {
				mapManufactures.put(Integer.valueOf(erzeugnisse.get(i).substring(0, 2)), 
						erzeugnisse.get(i).substring(3));
			}
			
			for(int i=0;i<produktelines.size();i++) {
			//zeile 0 = produkt, zeile 1 =zusammensetzung
				int amountofManufacture = 0;
				String tmpManufacut = null;
				if( i%2 == 0 ) { // gerade Zahlen
					
				}
				else { //ungerade zahlen
					Produkt pro1=new Produkt(produktelines.get(i-1));
					for(int x=0;x<produktelines.get(i).length();x=x+4) {
						
						
						//	System.out.println(tmplines.get(i).length() + "x-value:"+x);
							amountofManufacture = Integer.valueOf(produktelines.get(i).substring(x+0, x+2)); // Menge des Erzeugnis
							
							int manufactureNR = Integer.valueOf(produktelines.get(i).substring(x+2, x+4)); // Nr des Erzeugnis
						
							tmpManufacut=mapManufactures.get(manufactureNR);
							pro1.addManufacture(tmpManufacut, amountofManufacture);
							
					//		System.out.println("Produktname: "+tmplines.get(i-1)+"\nErzname: "+tmpManufacut+" Menge: "+amountofManufacture);
						
					}
					produktListe.add(pro1);
				}
				
				
			} // End of Create Produkt Liste
			return produktListe;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
} // end of getProduktliste
	
/*
private void saveEntry(final String entry) throws IOException {
    OutputStreamWriter osw = null;
    try {
        final FileOutputStream fos = openFileOutput("verleihnix.txt", MODE_PRIVATE | MODE_APPEND);
        osw = new OutputStreamWriter(fos);
        osw.write(entry);        
    } catch (FileNotFoundException e) { }        
    finally {
        osw.close();
    } 
}
	*/

}
 
So das Layout habe ich geändert auf ein LinearLayout vertical in dem mehrere Zeilen sind.

Die Frage bzw das Problem die/das ich jetzt habe:

Ich speichere die dynamischen Spinner und Adapter jeweils in einer ArrayList:

das problem dabei ist wenn ich einem bestehenden spinner an der Stelle (x) in der ArrayList einen neuen Adapter zuweise, dass ALLE Spinner diesen Adapter bekommen und nicht nur der eine.

Hat jemand von euch da eine Idee?
 
Meinst Du das hier?

Java:
sp_client.add(new Spinner(MainActivity.this));
adp_sp_client.add(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item,list));
adp_sp_client.get(numberofrows-1).setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp_client.get(numberofrows-1).setAdapter(adp_sp_client.get(numberofrows-1));

Du könntest auch zuerst komplett den Spinner mit Adapter erstellen und dann der Liste hinzufügen:

Java:
Spinner spinner = new Spinner(this);
ArrayAdapter adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, list);
spinner.setAdapter(adapter);
sp_client.add(spinner);

Den Adapter fügst Du zwar einer Liste hinzu, verwendest diese Liste aber nie mehr. Von dem her kann man sich das doch sparen, oder?!
 

Neue Themen


Zurück
Oben