Dynamically Adding the Spinner and Edittext with Delete
Programmatically Adding n Number of spinner and editext button with delete button
Main Activity:-
package com.example.dynamiccreation;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
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.LinearLayout;
import android.widget.ScrollView;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends Activity {
Context context;
ScrollView scrollView;
LinearLayout container;
LinearLayout layout,hor_layout;
int i = 1;
ArrayAdapter<String> dataAdapter;
List<EditText> allEds ;
List<Spinner> allSpinner ;
List<String> list;
private String[] productId = {};
private String[] product = {};
private String[] qty = {};
ArrayList<String> list_productId = new ArrayList<String>();
ArrayList<String> list_product;
ArrayList<String> list_qty = new ArrayList<String>();
SQLiteDatabase db = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
layout = (LinearLayout) findViewById(R.id.layout_horittal);
db = openOrCreateDatabase("dynamic.db", MODE_PRIVATE, null);
String sql_create = "create table if not exists valuecheck(_id integer primary key autoincrement,spinner varchar(120),qty varchar(120))";
String sql_product = "create table if not exists product(_id integer primary key autoincrement,productid varchar(120),product varchar(120),qty varchar(120))";
db.execSQL(sql_create);
db.execSQL(sql_product);
allEds = new ArrayList<EditText>();
list_product = new ArrayList<String>();
list_product.add("Select Proudct");
allSpinner = new ArrayList<Spinner>();
String spinner_value[] = {"A","B","C","D","E","F","G","H","I"};
list = new ArrayList<String>();
list.add("A+");
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
list.add("f");
list.add("G");
list.add("I");
list.add("J");
list.add("K");
list.add("L");
dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, list_product);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
String url = "http://192.168.2.16/mjn/roycerest/pick_productinput.php?module=mktgproductallocation&pickname=products&user=5007456";
Log.e("url for android", "======"+url);
new AsyncHttpTask().execute(url);
}
public void addButton(View view) {
final LinearLayout lin_layout = new LinearLayout(MainActivity.this);
lin_layout.setOrientation(LinearLayout.HORIZONTAL);
final Spinner spinner = new Spinner(MainActivity.this);
final EditText edittext = new EditText(MainActivity.this);
edittext.setHint("Please file the value");
final Button btn_get = new Button(MainActivity.this);
btn_get.setText("Delete");
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
int iv = 0;
String spin_value = spinner.getSelectedItem().toString();
int spinner_id = spinner.getId();
if(!(spin_value.equals("Select Proudct")))
{
if(spinner_id>=1)
{
for(int ij = 0;ij<allSpinner.size();ij++)
{
String spinnervalue = allSpinner.get(ij).getSelectedItem().toString();
if(spin_value.equals(spinnervalue))
{
iv++;
}
}
if(iv>=2)
{
spinner.setAdapter(dataAdapter);
Toast.makeText(getApplicationContext(), "Please select different product", Toast.LENGTH_SHORT).show();
}
}
}
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
final Button btn_Saveas = new Button(MainActivity.this);
btn_Saveas.setText("Save As");
btn_get.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// ((LinearLayout)layout.getParent()).removeView(lp);
lin_layout.removeView(btn_get);
lin_layout.removeView(edittext);
lin_layout.removeView(spinner);
allEds.remove(edittext);
allSpinner.remove(spinner);
// int ading = spinner.getId();
//
// String edit_value = edittext.getText().toString();
//
Toast.makeText(getApplicationContext(), "hello", Toast.LENGTH_SHORT).show();
}
});
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
spinner.setLayoutParams(lp);
edittext.setLayoutParams(lp);
btn_get.setLayoutParams(lp);
spinner.setAdapter(dataAdapter);
spinner.setId(i);
edittext.setId(i);
btn_get.setId(i);
allEds.add(edittext);
allSpinner.add(spinner);
lin_layout.addView(spinner);
lin_layout.addView(edittext);
lin_layout.addView(btn_get);
layout.addView(lin_layout);
i++;
}
public void saveButton(View view)
{
String inse_delete = "DELETE FROM valuecheck";
// String inse_alter ="ALTER TABLE valuecheck AUTO_INCREMENT = 1";
db.execSQL(inse_delete);
//db.execSQL(inse_alter);
for(int i=0; i < allEds.size(); i++)
{
int id = allEds.get(i).getId();
String edittestvalue = allEds.get(i).getText().toString();
String spinnervalue = allSpinner.get(i).getSelectedItem().toString();
Log.i(" ID===>", "ID==========>"+id);
Toast.makeText(getApplicationContext(),"Spinner"+spinnervalue+"Edit Text"+edittestvalue, Toast.LENGTH_SHORT).show();
Log.v(" vvvvvvvvvvvvvv==>Get All Value Dynamically", "Spinner"+spinnervalue+"Edit Text"+edittestvalue);
Log.i(" iiiiiiiiiiiii===> Get All Value Dynamically", "Spinner"+spinnervalue+"Edit Text"+edittestvalue);
String inse_query = "insert into valuecheck(spinner,qty) values('"+spinnervalue+"','"+edittestvalue+"')";
db.execSQL(inse_query);
Log.d("Insert query for valuecheck", ""+inse_query);
}
}
public void updateButton(View view)
{
String inse_select = "SELECT * FROM valuecheck";
Cursor cr_value = db.rawQuery(inse_select, null);
if(cr_value.getCount()>0)
{
while(cr_value.moveToNext())
{
final LinearLayout lin_layout1 = new LinearLayout(MainActivity.this);
lin_layout1.setOrientation(LinearLayout.HORIZONTAL);
final Spinner spinner1 = new Spinner(MainActivity.this);
final EditText edittext1 = new EditText(MainActivity.this);
edittext1.setHint("Please Fill the value");
final Button btn_get1 = new Button(MainActivity.this);
btn_get1.setText("Delete");
layout.removeView(lin_layout1);
btn_get1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// ((LinearLayout)layout.getParent()).removeView(lp);
lin_layout1.removeView(btn_get1);
lin_layout1.removeView(edittext1);
lin_layout1.removeView(spinner1);
allEds.remove(edittext1);
allSpinner.remove(spinner1);
// int ading = spinner.getId();
//
// String edit_value = edittext.getText().toString();
//
// Toast.makeText(getApplicationContext(), ""+ading+" "+edit_value, Toast.LENGTH_SHORT).show();
//
}
});
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
int ids = cr_value.getInt(cr_value.getColumnIndex("_id"));
String s_val = cr_value.getString(cr_value.getColumnIndex("spinner"));
String e_val = cr_value.getString(cr_value.getColumnIndex("qty"));
spinner1.setLayoutParams(lp);
edittext1.setLayoutParams(lp);
btn_get1.setLayoutParams(lp);
spinner1.setAdapter(dataAdapter);
spinner1.setSelection(getIndex(spinner1, s_val));
edittext1.setText(e_val);
// SelectSpinnerItemByValue(spinner1, s_val);
Log.i("=======================id============",""+ids);
spinner1.setId(i);
edittext1.setId(i);
btn_get1.setId(i);
//
allEds.add(edittext1);
allSpinner.add(spinner1);
lin_layout1.addView(spinner1);
lin_layout1.addView(edittext1);
lin_layout1.addView(btn_get1);
layout.addView(lin_layout1);
i++;
}
}
else
{
Toast.makeText(getApplicationContext(), "There is No Record in this Table", Toast.LENGTH_SHORT).show();
}
}
// public static void SelectSpinnerItemByValue(Spinner spnr, String value)
// {
// SimpleCursorAdapter adapter = (SimpleCursorAdapter) spnr.getAdapter();
// for (int position = 0; position < adapter.getCount(); position++)
// {
// if(adapter.getItemId(position) == value)
// {
// spnr.setSelection(position);
// return;
// }
// }
// }
//
private int getIndex(Spinner spinner1, String myString){
int index = 0;
for (int i=0;i<spinner1.getCount();i++){
if (spinner1.getItemAtPosition(i).equals(myString)){
index = i;
}
}
return index;
}
public void jsonButton(View view)
{
}
public class AsyncHttpTask extends AsyncTask<String, Void, Integer>
{
@Override
protected Integer doInBackground(String... params)
{
InputStream inputStream = null;
HttpURLConnection urlConnection = null;
Integer result = 0;
try
{
/* forming th java.net.URL object */
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
/* optional request header */
urlConnection.setRequestProperty("Content-Type", "application/json");
/* optional request header */
urlConnection.setRequestProperty("Accept", "application/json");
/* for Get request */
urlConnection.setRequestMethod("GET");
int statusCode = urlConnection.getResponseCode();
/* 200 represents HTTP OK */
if (statusCode == 200) {
inputStream = new BufferedInputStream(urlConnection.getInputStream());
String response = convertInputStreamToString(inputStream);
parseResult(response);
result = 1; // Successful
}else{
result = 0; //"Failed to fetch data!";
}
}
catch (Exception e)
{
Log.d("", e.getLocalizedMessage());
}
return result; //"Failed to fetch data!";
}
@SuppressWarnings("unchecked")
@Override
protected void onPostExecute(Integer result) {
/* Download complete. Lets update UI */
if(result == 1){
}else{
Log.e("", "Failed to fetch data!");
}
}
}
private String convertInputStreamToString(InputStream inputStream) throws IOException
{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null){
result += line;
}
/* Close Stream */
if(null!=inputStream){
inputStream.close();
}
return result;
}
private void parseResult(String result)
{
String inse_delete = "DELETE FROM product";
db.execSQL(inse_delete);
try
{
JSONObject response = new JSONObject(result);
JSONObject response1 = response.getJSONObject("message");
String su_msg = response1.getString("success");
if(su_msg.equals("true"))
{
//JSONArray posts = response1.optJSONArray("data");
JSONArray pose = response1.getJSONArray("data");
productId = new String[pose.length()];
product = new String[pose.length()];
qty = new String[pose.length()];
for(int i=0; i< pose.length();i++ )
{
//JSONObject post = posts.optJSONObject(i);
JSONObject post1 = pose.optJSONObject(i);
String d_productId= post1.getString("mktgproductallocationid");
String d_product = post1.optString("mktgproductallocationname");
String d_qty = post1.optString("quntity");
Log.e("===================", ""+d_productId);
productId[i] = ""+d_productId.toString();
product[i] = ""+d_product.toString();
qty[i] = ""+d_qty;
list_productId.add(d_productId);
list_product.add(d_product);
list_qty.add(d_qty);
String inse_product = "insert into product(productid,product,qty) values('"+d_productId+"','"+d_product+"','"+d_qty+"')";
db.execSQL(inse_product);
Log.i("================inser proucet",""+inse_product);
}
}
else
{
String str1 = "There is no value";
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<LinearLayout
android:id="@+id/LinearAdd"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="70"
android:orientation="horizontal" >
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.50"
android:onClick="addButton"
android:text="click to add" />
<Button
android:id="@+id/update_btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.50"
android:onClick="updateButton"
android:text="update" />
<Button
android:id="@+id/btn_jsonvalue"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.50"
android:onClick="jsonButton"
android:text="Json Value" />
</LinearLayout>
<ScrollView
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="70" >
<LinearLayout
android:id="@+id/layout_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/layout_horittal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<Button
android:id="@+id/btn_save_all"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="saveButton"
android:text="Save" />
</LinearLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>
Results:
this one another
No comments:
Post a Comment