Bulk saving Custom list view in android - android

I have created a custom list view with 7 fields which has been populated.
some of the fields have been took from local Db and set in list, else are edittexts. in each list row, i have also populated a save button. on that click i am able to save each list row in to local db. But i need to save the complete list in to local db in a single button click. Is it possible ??
My xml, Java class and adapter class is sending along with this.
XML class :
/>
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="#+id/spnrsangam"
/>
</TableRow>
<TableRow
android:weightSum="3"
android:layout_width="fill_parent"
>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Share Amount"
android:textSize="#dimen/Trans_heading_textsize"
android:layout_gravity="center_vertical"
android:textStyle="bold"
android:id="#+id/txtShreAmnt"
android:layout_weight=".8"
android:layout_marginLeft="15dp"
/>
<EditText
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textSize="#dimen/Trans_heading_textsize"
android:layout_gravity="center_vertical"
android:textStyle="bold"
android:id="#+id/edttxtShareAmnt"
android:layout_weight=".6"
android:inputType="number"
/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Deposit Amount"
android:textSize="#dimen/Trans_heading_textsize"
android:layout_gravity="center_vertical"
android:textStyle="bold"
android:id="#+id/txtAmnt"
android:layout_weight=".8"
android:layout_marginLeft="15dp"
/>
<EditText
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textSize="#dimen/Trans_heading_textsize"
android:layout_gravity="center_vertical"
android:textStyle="bold"
android:id="#+id/edttxtDepAmnt"
android:layout_weight=".6"
android:inputType="number"
/>
<Button
android:layout_width="0dp"
android:layout_height="30dp"
android:textSize="#dimen/Trans_heading_textsize"
android:layout_gravity="center_vertical"
android:text="Set"
android:background="#C5B2D8"
android:id="#+id/bttn_Show"
android:layout_weight=".2"
android:layout_marginRight="2dp"
/>
</TableRow>
</TableLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Transaction"
android:textColor="#0000ff"
android:textSize="#dimen/Trans_heading_textsize"
android:textStyle="bold|italic" />
</LinearLayout>
<!-- ............. Table heading ............... -->
<LinearLayout
android:id="#+id/header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp"
android:background="#1D1DF2"
android:orientation="horizontal" >
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginLeft="1dp"
android:layout_weight="1"
android:background="#C5B2D8"
android:gravity="center_horizontal"
android:text="Name"
android:textColor="#android:color/black"
android:textSize="#dimen/Trans_heading_textsize"
android:textStyle="bold"
android:layout_marginTop="1dp"
android:layout_marginBottom="1dp"/>
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginLeft="1dp"
android:layout_weight="1"
android:background="#C5B2D8"
android:gravity="center_horizontal"
android:text="Share No"
android:textColor="#android:color/black"
android:textSize="#dimen/Trans_heading_textsize"
android:textStyle="bold"
android:layout_marginTop="1dp"
android:layout_marginBottom="1dp"/>
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginLeft="1dp"
android:layout_weight="1"
android:background="#C5B2D8"
android:gravity="center_horizontal"
android:text="Dep No"
android:textColor="#android:color/black"
android:textSize="#dimen/Trans_heading_textsize"
android:textStyle="bold"
android:layout_marginTop="1dp"
android:layout_marginBottom="1dp" />
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginLeft="1dp"
android:layout_weight="1"
android:background="#C5B2D8"
android:gravity="center_horizontal"
android:text="Trans Type"
android:textColor="#android:color/black"
android:textSize="#dimen/Trans_heading_textsize"
android:textStyle="bold"
android:layout_marginTop="1dp"
android:layout_marginBottom="1dp" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="1dp"
android:layout_weight="1"
android:background="#C5B2D8"
android:gravity="center_horizontal"
android:text="Share Amt"
android:textColor="#android:color/black"
android:textSize="#dimen/Trans_heading_textsize"
android:textStyle="bold"
android:layout_marginTop="1dp"
android:layout_marginBottom="1dp" />
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginLeft="1dp"
android:layout_weight="1"
android:background="#C5B2D8"
android:gravity="center_horizontal"
android:text="Deposit Amt"
android:textColor="#android:color/black"
android:textSize="#dimen/Trans_heading_textsize"
android:textStyle="bold"
android:layout_marginTop="1dp"
android:layout_marginBottom="1dp"/>
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginLeft="1dp"
android:layout_weight="1"
android:background="#C5B2D8"
android:gravity="center_horizontal"
android:textColor="#android:color/black"
android:textStyle="bold"
android:layout_marginTop="1dp"
android:layout_marginBottom="1dp" />
</LinearLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/list_Trans_sheet"
android:layout_width="match_parent"
android:layout_height="#dimen/Trans_List_Height"
android:divider="#000000"
android:dividerHeight="1dp"
android:choiceMode="multipleChoice"/>
</LinearLayout>
</ScrollView>
<!-- ......................................... -->
</LinearLayout>
</LinearLayout>
Main Java Class is :
package com.example.esccocollection;
import java.util.ArrayList;
import java.util.List;
public class Sangam_Collection extends Activity {
ListView transview;
Custom_SangamCollection_Adapter adapter;
List<Retrieve_SangamCollection> translist;
EditText transAmnt, remark, dpsitamntset, shareAmtSet;
String str_agent_id2,idpref, str_setdepAmt, str_setShareAmt;
final AccountDBAdapter db = new AccountDBAdapter(this);
Spinner spnr_sangam;
String str_spinner, str_sangam_name;
Context context;
Button bttnset, bttnSave;
ArrayList<String> sangamnames = new ArrayList<String>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newtransaction_sheet);
shareAmtSet=(EditText)findViewById(R.id.edttxtShareAmnt);
dpsitamntset=(EditText)findViewById(R.id.edttxtDepAmnt);
bttnset = (Button)findViewById(R.id.bttn_Show);
transview = (ListView) findViewById(R.id.list_Trans_sheet);
str_setdepAmt="";
str_setShareAmt= "";
bttnset.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
str_setdepAmt= dpsitamntset.getText().toString();
str_setShareAmt= shareAmtSet.getText().toString();
str_spinner=spnr_sangam.getSelectedItem().toString();
getsangam2dtls(str_spinner);
}
private void getsangam2dtls(String str_spinner) {
// TODO Auto-generated method stub
try {
db.open();
// String Maxcramnt = db.getTransSheetdetails();
//Cursor cur = db.getTransSheetdetails(str_spinner);
Cursor cur = db.getTransnewSheetdetails(str_spinner);
final String[] arrayAcc = new String[cur.getCount()];
String[] arrayName = new String[cur.getCount()];
String[] arrayBalAmnt = new String[cur.getCount()];
int i = 0;
while (cur.moveToNext()) {
String accArray = cur.getString(cur
.getColumnIndex("Acc_Type"));
String nameArray = cur.getString(cur
.getColumnIndex("Acc_No"));
String tamntArray = cur.getString(cur
.getColumnIndex("Dep_No"));
arrayAcc[i] = accArray.toString();
arrayName[i] = nameArray.toString();
arrayBalAmnt[i] = tamntArray.toString();
i++;
db.close();
}
if(arrayAcc.length!=0){
translist = new ArrayList<Retrieve_SangamCollection>();
for (int m = 0; m <= cur.getCount(); m++) {
//Log.e("Cust name", ""+arrayName[m]);
Retrieve_SangamCollection ret = new
Retrieve_SangamCollection
(arrayAcc[m],arrayName[m],arrayBalAmnt[m],str_setShareAmt,
str_setdepAmt);
translist.add(ret);
listset();
}
}else {
transview.setAdapter(null);
Toast.makeText(getApplicationContext(), "No data to display", 5000).show();
}
} catch (Exception e) {
// TODO: handle exception
Log.e("Trans retlist ", ""+e.getMessage());
}
// TODO Auto-generated method stub
}
private void listset() {
// TODO Auto-generated method stub
try {
transview = (ListView) findViewById(R.id.list_Trans_sheet);
transview.setAdapter(null);
adapter = new Custom_SangamCollection_Adapter
(Sangam_Collection.this, R.layout.trans_pop_list, translist);
transview.setAdapter(adapter);
adapter.notifyDataSetChanged();
} catch (Exception e) {
// TODO: handle exception
Log.e("tr amount is:", "error..");
}
get_list();
}
});
spnr_sangam=(Spinner) findViewById(R.id.spnrsangam);
/////------------- to get sangam name from shared pref -----------------
SharedPreferences pr_sangam_name=getSharedPreferences("pr_sangam_name", MODE_MULTI_PROCESS);
str_sangam_name=pr_sangam_name.getString("sangam_name", "");
Log.e("Sangam name in loanform", ""+str_sangam_name);
sangamnames.add(str_sangam_name);
final ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, sangamnames);
spnr_sangam.setAdapter(adapter1);
/*
String[] items = new String[] {"sangam1", "sangam2" };
final ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, items);
spnr_sangam.setAdapter(adapter1);*/
// str_spinner=spnr_sangam.getSelectedItem().toString();
// String sanagam="sangam1";
/*db.open();
String Maxcramnt = db.getTransSheet(sanagam);
Toast.makeText(getApplicationContext(), ""+Maxcramnt, 5000).show();
db.open();*/
// TODO Auto-generated method stub
spnr_sangam.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
try {
// TODO Auto-generated method stub
// str_spinner=spnr_sangam.getSelectedItem().toString();
str_spinner=spnr_sangam.getSelectedItem().toString();
getsangam2dtls(str_spinner);
} catch (Exception e) {
// TODO: handle exception
}
// return false;
}
private void getsangam2dtls(String str_spinner) {
// TODO Auto-generated method stub
try {
db.open();
// String Maxcramnt = db.getTransSheetdetails();
// Cursor cur = db.getTransSheetdetails(str_spinner);
Cursor cur = db.getTransnewSheetdetails(str_spinner);
final String[] arrayAcc = new String[cur.getCount()];
String[] arrayName = new String[cur.getCount()];
String[] arrayBalAmnt = new String[cur.getCount()];
int i = 0;
while (cur.moveToNext()) {
String accArray = cur.getString(cur
.getColumnIndex("Acc_Type"));
String nameArray = cur.getString(cur
.getColumnIndex("Acc_No"));
String tamntArray = cur.getString(cur
.getColumnIndex("Dep_No"));
arrayAcc[i] = accArray.toString();
arrayName[i] = nameArray.toString();
arrayBalAmnt[i] = tamntArray.toString();
i++;
db.close();
}
if(arrayAcc.length!=0){
translist = new ArrayList<Retrieve_SangamCollection>();
for (int m = 0; m <= cur.getCount(); m++) {
// Log.e("Cust name", ""+arrayBalAmnt[m]);
Retrieve_SangamCollection ret = new Retrieve_SangamCollection(arrayAcc[m], arrayName[m], arrayBalAmnt[m], str_setShareAmt, str_setdepAmt);
translist.add(ret);
listset();
}
}else {
transview.setAdapter(null);
Toast.makeText(getApplicationContext(), "No data to display", 5000).show();
}
} catch (Exception e) {
// TODO: handle exception
Log.e("Trans retlist ", ""+e.getMessage());
}
}
private void listset() {
// TODO Auto-generated method stub
try {
transview = (ListView) findViewById(R.id.list_Trans_sheet);
transview.setAdapter(null);
adapter = new
Custom_SangamCollection_Adapter(Sangam_Collection.this,
R.layout.trans_pop_list, translist);
transview.setAdapter(adapter);
adapter.notifyDataSetChanged();
} catch (Exception e) {
// TODO: handle exception
Log.e("tr amount is:", "error..");
}
}
/*private void getsangam1dtls(String str_spinner) {
// TODO Auto-generated method stub
try {
db.open();
// String Maxcramnt = db.getTransSheetdetails();
Cursor cur = db.getTransSheetdetails(str_spinner);
//Cursor cur = db.getTransSheetdetails();
final String[] arrayAcc = new String[cur.getCount()];
String[] arrayName = new String[cur.getCount()];
String[] arrayBalAmnt = new String[cur.getCount()];
int i = 0;
while (cur.moveToNext()) {
String accArray = cur.getString(cur
.getColumnIndex("Acc_No"));
String nameArray = cur.getString(cur
.getColumnIndex("Cust_Name"));
String tamntArray = cur.getString(cur
.getColumnIndex("Bal_Amt"));
arrayAcc[i] = accArray.toString();
arrayName[i] = nameArray.toString();
arrayBalAmnt[i] = tamntArray.toString();
i++;
db.close();
}
translist = new ArrayList<retrieveTrans>();
for (int m = 0; m <= cur.getCount(); m++) {
//Log.e("Cust name", ""+arrayName[m]);
retrieveTrans ret = new retrieveTrans(arrayAcc[m],
arrayName[m], arrayBalAmnt[m]);
translist.add(ret);
listset();
}
} catch (Exception e) {
// TODO: handle exception
Log.e("Trans retlist ", ""+e.getMessage());
}
//Cursor cur
}*/
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
try {
transview = getListView();
transview.setLongClickable(true);
transview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
transview.setMultiChoiceModeListener(new MultiChoiceModeListener() {
#Override
public boolean onPrepareActionMode(ActionMode arg0, Menu arg1) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onDestroyActionMode(ActionMode arg0) {
// TODO Auto-generated method stub
}
#Override
public boolean onCreateActionMode(ActionMode arg0, Menu arg1) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onActionItemClicked(ActionMode arg0, MenuItem arg1) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "on item clicked", 5000).show();
return false;
}
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "on item checked statmnt", 5000).show();
}
});
} catch (Exception e) {
// TODO: handle exception
Log.e("List work ", ""+e.getMessage());
}
}
private ListView getListView() {
// TODO Auto-generated method stub
return null;
}
protected void get_list() {
// TODO Auto-generated method stub
for(int i = 0;i<=transview.getCount();i++);
{
}
}
};
this is adapter class
import java.text.SimpleDateFormat;
#SuppressWarnings("serial")
public class Custom_SangamCollection_Adapter extends BaseAdapter {
public ArrayList<Retrieve_SangamCollection> ret_arrArrayList;
private List<Retrieve_SangamCollection> ret_translist;
private LayoutInflater inflater;
ArrayAdapter<String> adapterspin;
String time, currntdate, status;
String Maxcramnt, balamount,str_useridpref;
double Mamount, Bamount, actualamnt;
String idpref, str_agent_id2, accno;
int trcheck;
int d = 0;
String tramnt = "", remarks = "";
Context context;
int count;
public Custom_SangamCollection_Adapter(Sangam_Collection sangam_Collection,
int transListPop, List<Retrieve_SangamCollection> translist) {
// TODO Auto-generated constructor stub
super();
this.ret_translist = translist;
inflater = LayoutInflater.from(sangam_Collection);
this.ret_arrArrayList = new ArrayList<Retrieve_SangamCollection>();
this.ret_arrArrayList.addAll(translist);
this.context = sangam_Collection;
}
public Custom_SangamCollection_Adapter(Context context2) {
// TODO Auto-generated constructor stub
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return ret_translist.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return ret_translist.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
class ViewHolder {
TextView acc_txt, name_txt, balAmnt_txt;
Spinner trans_spinner;
EditText transAmnt_edittxt, remarks_edittxt;
Button save;
}
#Override
public View getView(final int pos, View cv, ViewGroup arg2) {
// TODO Auto-generated method stub
try {
final ViewHolder holder;
View row = cv;
int p = pos;
// Log.e("position of getview:", "" + p);
if (cv == null) {
cv = inflater.inflate(R.layout.trans_pop_list, null);
holder = new ViewHolder();
holder.acc_txt = (TextView) cv
.findViewById(R.id.txtTransAccNo_pop);
holder.name_txt = (TextView) cv
.findViewById(R.id.txtTransName_pop);
holder.balAmnt_txt = (TextView) cv
.findViewById(R.id.txtTransBalAmnt_pop);
holder.trans_spinner = (Spinner) cv
.findViewById(R.id.spinTrans_Type);
holder.transAmnt_edittxt = (EditText) cv
.findViewById(R.id.editTransAmnt_pop);
holder.save = (Button) cv.findViewById(R.id.save);
holder.remarks_edittxt = (EditText) cv
.findViewById(R.id.editRemarks_pop);
cv.setTag(holder);
} else {
holder = (ViewHolder) cv.getTag();
}
holder.acc_txt.setText("" + ret_translist.get(pos).getRetAccNo());
String hari = holder.acc_txt.getText().toString();
holder.name_txt.setText("" + ret_translist.get(pos).getRetName());
holder.balAmnt_txt.setText(""
+ ret_translist.get(pos).getRetBalAmnt());
holder.remarks_edittxt.setText(""+ret_translist.get(pos).getsetdpAmnt());
holder.transAmnt_edittxt.setText(""+ret_translist.get(pos).getsetShrAmt());
// holder.remarks_edittxt.setText("100");
/* ************* Declaring spinner items ************** */
String[] items = new String[] { "credit" };
final ArrayAdapter<String> adapterspin = new ArrayAdapter<String>(
context, android.R.layout.simple_spinner_item, items);
final String haris = holder.name_txt.getText().toString();
holder.trans_spinner.setAdapter(adapterspin);
/* ******************* Save button Click ******************* */
holder.save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int position = pos;
final String accno = holder.name_txt.getText().toString();
final String tramnt = holder.transAmnt_edittxt.getText()
.toString();
String remarks = holder.remarks_edittxt.getText()
.toString();
final String spinner = holder.trans_spinner
.getSelectedItem().toString();
Log.e("accno:", "" + accno);
Log.e("name :", "" + tramnt);
Log.e("position:", "" + position);
Log.e("remark:", "" + remarks);
Log.e("spinner:", "" + spinner);
/************* time and date *************/
// ----------Time----------**
Calendar c = Calendar.getInstance();
time = (c.get(Calendar.HOUR) + ":" + c.get(Calendar.MINUTE)
+ ":" + c.get(Calendar.SECOND));
Log.e("Current Time", " " + time);
// -----------Date---------**
Date now = new Date();
Date alsoNow = Calendar.getInstance().getTime();
currntdate = new SimpleDateFormat("M-d-yyyy").format(now);
Log.e("Date ", " " + currntdate);
/* **************** Check if all fields are Filled **************** */
status = new String("y");
if (tramnt.equals("")) {
Toast.makeText(arg0.getContext(),
"enter Transaction amount", 5000).show();
Log.e("if cndition", " " + tramnt);
} else if (spinner.equals("Type")) {
Toast.makeText(arg0.getContext(),
"Select Transaction type", 5000).show();
Log.e("if cndition", " " + tramnt);
}
else {
if (remarks.equals("")) {
remarks = "null";
}
/******************** declaration for dbcall *********************/
try{
SharedPreferences pr_acc_info=context.
getSharedPreferences("pr_acc_info",
context.MODE_MULTI_PROCESS);
str_useridpref=pr_acc_info.getString("userid","");
// String str_brnamepref=pr_acc_info.getString("branchname","");
Log.e("userid in custom sangamcollction", ""+str_useridpref);
}catch (Exception e) {
// TODO: handle exception
Log.e("", e.toString());
}
AccountDBAdapter db = new AccountDBAdapter(context);
Sangam_Collection ts = new Sangam_Collection();
try {
db.open();
String accid = db.getAccID(accno);
String Maxcramnt = db.getMaxCrAmnt(accno);
db.close();
Log.e("tramnt", " " + tramnt);
Log.e("Mamount", " " + Mamount);
actualamnt = 0;
String userId = "" + 2;
Mamount = Double.parseDouble(Maxcramnt);
Bamount = Double.parseDouble(tramnt);
Log.e("Mamount", " " + Mamount);
if(Bamount<Mamount)
{
Mamount = Double.parseDouble(Maxcramnt);
//Bamount = Double.parseDouble(tramnt);
actualamnt = Mamount - Bamount;
balamount = "" + actualamnt;
db.open();
db.update_MaxCrAmnt(balamount, accid);
db.close();
db.open();
db.insertTransactionTable(accid.toString(),
currntdate.toString(), spinner.toString(),
tramnt.toString(), str_useridpref.toString(),
time.toString(), remarks.toString(),
status.toString());
db.close();
holder.save.setText("SAVED");
holder.save.setBackgroundColor(Color.GRAY);
}
else
{
Toast.makeText(context, "Your Amount Exceeds your Balance", 5000).show();
}
} catch (Exception e) {
Log.e("error", e.getMessage());
}
}
}
});
} catch (Exception c) {
Log.e("adapter error", "" + c.getMessage());
}
return cv;
}
}
Need your valuable help.. Thanks in advance.

Related

No error when updating, but the image cannot updated android sqlite

So I have an SQLite database. I try to update and there is no error in my android application. When I update only the name or the cost, it successfully updated but the image not showing in my gridview. But when I Update only the image, it is successfully updated.Can someone please help me out here!
this my Database Class:
public class Database extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "mydaringdb";
private static final int DATABASE_VERSION = 2;
public static final String TABLE_PRODUK = "produk";
public static final String KEY_ID_PRODUK = "id";
public static final String KEY_NAMA_PRODUK = "nama_produk";
public static final String KEY_HARGA_PRODUK = "harga_produk";
public static final String KEY_GAMBAR_PRODUK = "gambar_produk";
//for showing 1 product
public ModelProduk getnama(int selection) {
SQLiteDatabase db = this.getReadableDatabase();
String cb = "SELECT * FROM " + TABLE_PRODUK + " WHERE " + KEY_ID_PRODUK + "= '" + selection + "'";
Cursor cursor = db.rawQuery(cb, null);
if (cursor != null)
cursor.moveToFirst();
ModelProduk modelProduk = new ModelProduk();
modelProduk.set_id(Integer.parseInt(cursor.getString(0)));
modelProduk.set_nama(cursor.getString(1));
modelProduk.set_harga(Integer.parseInt(cursor.getString(2)));
modelProduk.set_gambar(cursor.getBlob(3));
return modelProduk;
}
//for update 1 product
public void update(ModelProduk modelProduk) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAMA_PRODUK, modelProduk.get_nama());
values.put(KEY_HARGA_PRODUK, modelProduk.get_harga());
values.put(KEY_GAMBAR_PRODUK, modelProduk.get_gambar());
String where = "id=?";
String[] whereArgs = new String[] {String.valueOf(modelProduk.get_id())};
// update baris
db.update(TABLE_PRODUK, values, where, whereArgs);
}
My update class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_produk);
init();
tambahgambaru.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showFileChooser();
}
});
simpandatau.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
modelProduk.set_nama(deskripsiu.getText().toString());
modelProduk.set_harga(Integer.parseInt(harga_produku.getText().toString()));
modelProduk.set_gambar(getImageByte(bitmap));
db.update(modelProduk);
Toast.makeText(getApplicationContext(), "Data Berhasil Diubah!", Toast.LENGTH_SHORT).show();
}
});
kembaliu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(UpdateProduk.this, Produk.class);
startActivity(i);
finish();
}
});
}
public void refresh(){
produklist = new ArrayList<>();
adapter = new ProdukAdapter( this, produklist);
produklist.clear();
produklist.addAll(db.getAllProduk());
adapter.notifyDataSetChanged();
}
private void init(){
pilih = getIntent().getIntExtra("id_produk", 0);
db = new Database(this);
modelProduk = db.getnama(pilih);
gambar_produku = (ImageView) findViewById(R.id.pilihgambaru);
tambahgambaru = (Button) findViewById(R.id.btaddu);
simpandatau = (Button) findViewById(R.id.btsimpanu);
deskripsiu = (EditText) findViewById(R.id.etdesku);
harga_produku = (EditText) findViewById(R.id.ethargau);
kembaliu = (Button) findViewById(R.id.btkembaliu);
deskripsiu.setText(modelProduk.get_nama());
harga_produku.setText(String.valueOf(modelProduk.get_harga()));
gambar_produku.setImageBitmap(bitmap(modelProduk.get_gambar()));
}
public void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Pilih Gambar"), 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode==RESULT_OK) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
gambar_produku.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public byte[] getImageByte(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
byte imageInByte[]=null;
if(bitmap!=null) {
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, stream);
imageInByte=stream.toByteArray();
}
return imageInByte;
}
public Bitmap bitmap (byte[] byteImage){
byte[] outImage = byteImage;
Bitmap image ;
if (outImage != null){
ByteArrayInputStream imageStream = new ByteArrayInputStream(outImage);
image = BitmapFactory.decodeStream(imageStream);
}else {
image= null;
}
return image;
}
}
my update.xml:
<ImageView
android:id="#+id/pilihgambaru"
android:layout_width="150dp"
android:layout_height="150dp"
android:src="#mipmap/ic_launcher"
android:layout_centerHorizontal="true"
/>
<Button
android:id="#+id/btaddu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/pilihgambaru"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:text="pilih gambar"
android:layout_centerHorizontal="true"
/>
<EditText
android:id="#+id/etdesku"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginLeft="10dp"
android:layout_below="#id/btaddu"
android:layout_centerHorizontal="true"
android:hint="Masukkan Deskripsi Barang"
android:inputType="textMultiLine"
android:maxLength="100"
/>
<EditText
android:id="#+id/ethargau"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_below="#id/etdesku"
android:layout_marginTop="10dp"
android:layout_centerHorizontal="true"
android:hint="Masukkan Harga Barang"
android:inputType="number"
android:maxLength="10"
/>
<Button
android:id="#+id/btsimpanu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/ethargau"
android:layout_marginTop="10dp"
android:text="simpan"
android:layout_marginLeft="100dp"
android:layout_centerHorizontal="true"
/>
<Button
android:id="#+id/btkembaliu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/btsimpanu"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:text="ke produk"
/>

How to dynamically add suggestions to autocompletetextview with preserving character status along with images

Currently I am using code to give text suggestion. I would like to add another text and image. How do I do that? Currently, I am using the code below.I shows text but image is not displayed .How do I set the image ?
public class AutoCompleteTextViewActivity extends Activity{
ImageLoader imageLoader;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisc(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
.defaultDisplayImageOptions(defaultOptions)
.build();
ImageLoader.getInstance().init(config);
AutoCompleteTextView actv = new AutoCompleteTextView(this);
actv.setThreshold(1);
final String[] from = {BaseColumns._ID, "name", "artist", "title"};
int[] to = {R.id.list_image, R.id.textView1, R.id.textView2, R.id.textView3};
final SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.list_row, null, from, to);
adapter.setStringConversionColumn(1);
ViewBinder viewBinder = new ViewBinder() {
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
if (columnIndex == 0) {
ImageView iv = (ImageView) view;
Bitmap bitmap = cursor.getExtras().getParcelable("image");
if (bitmap != null) {
iv.setImageBitmap(bitmap);
}
return true;
}
return false;
}
};
adapter.setViewBinder(viewBinder);
FilterQueryProvider provider = new FilterQueryProvider() {
ExecutorService mPool = Executors.newCachedThreadPool();
Uri URI = Uri.parse("adapter://autocomplete");
public Cursor runQuery(CharSequence constraint) {
if (constraint == null) {
return null;
}
try {
return callWebService(constraint, from);
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
// here you make the web request
private Cursor callWebService(CharSequence constraint, String[] columnNames) throws JSONException {
Log.d("TAG", "callWebService for: " + constraint);
MatrixCursor cursor = new MyMatrixCursor(columnNames);
// TODO do real network request
// call web service here and keep the result in "jsonStr"
// String a=constraint;
JSONObject json=JSONfunctions.getJSONfromURL("http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist="+ constraint +"&api_key=63692beaaf8ba794a541bca291234cd3&format=json");
JSONObject js1=json.getJSONObject("artist");
JSONObject js=js1.getJSONObject("similar");
JSONArray resultArray = js.getJSONArray("artist");
int length = resultArray.length();
for (int i = 0; i < length; i++) {
String data = resultArray.getJSONObject(i).getString("name");
String dataimage = resultArray.getJSONObject(i).getJSONArray("image").getJSONObject(i).getString("#text");
cursor.newRow().add(i)
.add(data)
.add(data)
.add(data);
String link = dataimage;
// get cached Bundle based on "link" (use HashMap<String, Bundle>)
// or if new link initiate async request for getting the bitmap
// TODO implement HashMap caching
// new async request
Bundle extras = new Bundle();
try {
mPool.submit(new ImageRequest(link, extras));
} catch (MalformedURLException e) {
e.printStackTrace();
}
cursor.respond(extras);
}
cursor.setNotificationUri(getContentResolver(), URI);
return cursor;
}
class ImageRequest implements Runnable {
private URL mUrl;
private Bundle mExtra;
public ImageRequest(String link, Bundle extra) throws MalformedURLException {
mUrl = new URL(link);
mExtra = extra;
}
public void run() {
String TAG="log";
// TODO do real network request
// simulate network delay
// Log.d(TAG, "getting " + mUrl);
// try {
// Thread.sleep(2000 + (long) (4000 * Math.random()));
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
Bitmap b = imageLoader.loadImageSync(mUrl.toString());
// Bitmap b = BitmapFactory.decodeResource(getResources(), mUrl.toString());
mExtra.putParcelable("image", b);
getContentResolver().notifyChange(URI, null);
Log.d(TAG, "run got a bitmap " + b.getWidth() + "x" + b.getHeight());
}
}
};
adapter.setFilterQueryProvider(provider);
actv.setAdapter(adapter);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
setContentView(actv, params);
}
}
///////////////
MyMatrixCursor
//////////
public class MyMatrixCursor extends MatrixCursor {
List<Bundle> mBundles = new ArrayList<Bundle>();
public MyMatrixCursor(String[] columnNames) {
super(columnNames);
}
#Override
public Bundle respond(Bundle extras) {
mBundles.add(extras);
return extras;
}
#Override
public Bundle getExtras() {
return mBundles.get(mPos);
}
}
////////
JSONfunctions
///////
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url){
InputStream is = null;
String result = "";
JSONObject jArray = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
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.w("log_tag", "Error converting result "+e.toString());
}
try{
jArray = new JSONObject(result);
}catch(JSONException e){
Log.w("log_tag", "Error parsing data "+e.toString());
}
return jArray;
}
}
////////
main.xml
///
<?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:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pick Artist"
android:textAppearance="?android:attr/textAppearanceLarge" />
<AutoCompleteTextView
android:id="#+id/actv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:completionThreshold="1"> <requestFocus />
</AutoCompleteTextView>
<TextView
android:id="#+id/selection"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
/////
list_row.xml
///
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#android:color/white"
android:orientation="horizontal"
android:padding="5dip" >
<!-- ListRow Left sied Thumbnail image -->
<LinearLayout android:id="#+id/thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="3dip"
android:layout_alignParentLeft="true"
android:layout_marginRight="5dip">
<ImageView
android:id="#+id/list_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:maxWidth="42dp"
android:maxHeight="42dp"
android:src="#drawable/ic_launcher"
android:scaleType="fitCenter"
android:layout_marginLeft="3dp"/>
</LinearLayout>
<!-- Title Of Song-->
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/thumbnail"
android:layout_toRightOf="#+id/thumbnail"
android:text="test"
android:textColor="#040404"
android:typeface="sans"
android:textSize="15dip"
android:textStyle="bold"/>
<!-- Artist Name -->
<!-- Rightend Duration -->
<!-- Rightend Arrow -->
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_centerVertical="true"
android:text="test"
android:textColor="#040404"
android:textSize="5dip"
android:textStyle="bold"
android:typeface="sans" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/thumbnail"
android:layout_toRightOf="#+id/thumbnail"
android:text="test"
android:textColor="#040404"
android:textSize="15dip"
android:textStyle="bold"
android:typeface="sans" />
</RelativeLayout>
///
Manifest
///
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.example"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:label="#string/app_name"
android:name=".AutoCompleteTextViewActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
ok try this:
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
AutoCompleteTextView actv = new AutoCompleteTextView(this);
actv.setThreshold(1);
String[] from = {"name"};
int[] to = {android.R.id.text1};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_dropdown_item_1line, null, from, to) {
// required for Spanned data
#Override
public void bindView(View view, Context context, Cursor cursor) {
MyCursor c = (MyCursor) cursor;
TextView tv = (TextView) view;
tv.setText(c.getSpanned());
}
// required for Spanned data
#Override
public CharSequence convertToString(Cursor cursor) {
MyCursor c = (MyCursor) cursor;
return c.getSpanned();
}
};
FilterQueryProvider provider = new FilterQueryProvider() {
#Override
public Cursor runQuery(CharSequence constraint) {
if (constraint == null) {
return null;
}
MyCursor c = new MyCursor();
// fake web service responses
List<String> names = callFakeWebService(constraint);
int i = 0;
for (String name: names) {
SpannableStringBuilder ssb = new SpannableStringBuilder(name);
int start = name.indexOf(" ");
ForegroundColorSpan what = new ForegroundColorSpan(0xffff0000);
ssb.setSpan(what, start + 1, ssb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
c.newRow().add(i++).add(name);
c.addSpanned(ssb);
}
return c;
}
// fake web service request
private List<String> callFakeWebService(CharSequence constraint) {
Log.d(TAG, "callFakeWebService for: " + constraint);
String[] namesArr = {
"Mark Smith",
"Monica Thompson",
"John White",
"Jane Brown"
};
String stringConstraint = constraint.toString().toLowerCase();
List<String> names = new ArrayList<String>();
for (int i = 0; i < namesArr.length; i++) {
String name = namesArr[i];
if (name.toLowerCase().startsWith(stringConstraint)) {
names.add(name);
}
}
return names;
}
};
adapter.setFilterQueryProvider(provider);
actv.setAdapter(adapter);
ll.addView(actv);
TextView tv = new TextView(this);
tv.setTextSize(32);
tv.setTextColor(0xffff0000);
tv.setText("type one of:\n mark,\n monica,\n john\n jane");
ll.addView(tv);
setContentView(ll);
where custom Cursor could look like this (it is minimalistic version supporting only one Spanned in a row):
static class MyCursor extends MatrixCursor {
private static final String[] NAMES = {BaseColumns._ID, "name"};
private ArrayList<Spanned> mSpannedList;
public MyCursor() {
super(NAMES);
mSpannedList = new ArrayList<Spanned>();
}
public void addSpanned(Spanned s) {
mSpannedList.add(s);
}
public Spanned getSpanned() {
return mSpannedList.get(mPos);
}
}
EDIT with no Spanned text:
AutoCompleteTextView actv = new AutoCompleteTextView(this);
actv.setThreshold(1);
final String[] from = {BaseColumns._ID, "name", "artist", "title"};
int[] to = {R.id.list_image, R.id.textView1, R.id.textView2, R.id.textView3};
final SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.list_row, null, from, to);
adapter.setStringConversionColumn(1);
ViewBinder viewBinder = new ViewBinder() {
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
if (columnIndex == 0) {
ImageView iv = (ImageView) view;
Bitmap bitmap = cursor.getExtras().getParcelable("image");
if (bitmap != null) {
iv.setImageBitmap(bitmap);
}
return true;
}
return false;
}
};
adapter.setViewBinder(viewBinder);
FilterQueryProvider provider = new FilterQueryProvider() {
ExecutorService mPool = Executors.newCachedThreadPool();
Uri URI = Uri.parse("adapter://autocomplete");
public Cursor runQuery(CharSequence constraint) {
if (constraint == null) {
return null;
}
try {
return callWebService(constraint, from);
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
// here you make the web request
private Cursor callWebService(CharSequence constraint, String[] columnNames) throws JSONException {
Log.d("TAG", "callWebService for: " + constraint);
MatrixCursor cursor = new MyMatrixCursor(columnNames);
// TODO do real network request
// call web service here and keep the result in "jsonStr"
String jsonStr = "{\"ResultArray\":[{\"data\":{ \"sno\":\"sno1\", \"date\":\"2011-08-21 14:27:09\", \"user\":\"1\", \"link\":\"http://scm-l3.technorati.com/11/11/17/56749/google-docs-revision.jpg?t=20111117074048\", \"name\":\"Aa\" }},{\"data\":{ \"sno\":\"sno2\", \"date\":\"2011-08-21 14:28:09\", \"user\":\"2\", \"link\":\"http://kcclaveria.com/wp-content/uploads/2013/02/google-panda-penguin.jpg\", \"name\":\"Bb\" }}]}";
JSONObject json = new JSONObject(jsonStr);
JSONArray resultArray = json.getJSONArray("ResultArray");
int length = resultArray.length();
for (int i = 0; i < length; i++) {
JSONObject data = resultArray.getJSONObject(i).getJSONObject("data");
cursor.newRow().add(i)
.add(data.getString("name"))
.add(data.getString("user"))
.add(data.getString("sno"));
String link = data.getString("link");
// get cached Bundle based on "link" (use HashMap<String, Bundle>)
// or if new link initiate async request for getting the bitmap
// TODO implement HashMap caching
// new async request
Bundle extras = new Bundle();
try {
mPool.submit(new ImageRequest(link, extras));
} catch (MalformedURLException e) {
e.printStackTrace();
}
cursor.respond(extras);
}
cursor.setNotificationUri(getContentResolver(), URI);
return cursor;
}
class ImageRequest implements Runnable {
private URL mUrl;
private Bundle mExtra;
public ImageRequest(String link, Bundle extra) throws MalformedURLException {
mUrl = new URL(link);
mExtra = extra;
}
#Override
public void run() {
// TODO do real network request
// simulate network delay
Log.d(TAG, "getting " + mUrl);
try {
Thread.sleep(2000 + (long) (4000 * Math.random()));
} catch (InterruptedException e) {
e.printStackTrace();
}
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
mExtra.putParcelable("image", b);
getContentResolver().notifyChange(URI, null);
Log.d(TAG, "run got a bitmap " + b.getWidth() + "x" + b.getHeight());
}
}
};
adapter.setFilterQueryProvider(provider);
actv.setAdapter(adapter);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
setContentView(actv, params);
and the custom MatrixCursor:
class MyMatrixCursor extends MatrixCursor {
List<Bundle> mBundles = new ArrayList<Bundle>();
public MyMatrixCursor(String[] columnNames) {
super(columnNames);
}
#Override
public Bundle respond(Bundle extras) {
mBundles.add(extras);
return extras;
}
#Override
public Bundle getExtras() {
return mBundles.get(mPos);
}
}

Searching of Customlist view not working

I am trying to built search functionality on custom listView but it is not working..list is not changing according to EditText words changes..
listplaceholder.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/edtSearch"
android:hint="Search"/>
<ListView
android:id="#id/android:list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawSelectorOnTop="false" />
</LinearLayout>
my_custom_layout.xml
<?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="wrap_content"
android:orientation="horizontal"
android:padding="5dp" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="70dp"
android:layout_height="70dp"
android:src="#drawable/icon" />
<FrameLayout
android:id="#+id/frame"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Button"
/>
<LinearLayout
android:id="#+id/ll1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/a"
android:orientation="vertical" >
<TextView
android:id="#+id/from_user"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000" />
<TextView
android:id="#+id/from_user_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000" />
</LinearLayout>
</FrameLayout>
</LinearLayout>
Main.java
public class Main extends ListActivity {
/** Called when the activity is first created. */
ImageView img, img1;
private AdapterClass adapter;
private String reviewImageLink;
private static final String TAG = "PRANJAL";
private boolean isImage = false;
String fileName[] = new String[10];
private String imgurl;
ArrayList<HashMap<String, String>> searchResult;
private EditText edtSearch;
private ListView list;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
edtSearch = (EditText) findViewById(R.id.edtSearch);
list = (ListView) findViewById(android.R.id.list);
// list = (LinearLayout) findViewById(R.id.list);
final ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
JSONObject json = JSONfunctions
.getJSONfromURL("http://23.21.228.8/PlutoApp_Beta/consumer_dash/"
+ "checkIn_confirmation_related_record.php?lat=18.535787&lng=73.891889");
try {
JSONArray earthquakes = json.getJSONArray("Display");
for (int i = 0; i < earthquakes.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = earthquakes.getJSONObject(i);
map.put("Name", e.getString("name"));
map.put("Vicinity", e.getString("vicinity"));
map.put("logo", e.getString("logo"));
imgurl = e.getString("logo");
// Toast.makeText(getApplicationContext(), imgurl,
// Toast.LENGTH_SHORT).show();
imgurl = e.getString("logo");
// Toast.makeText(getApplicationContext(), imgurl,
// Toast.LENGTH_SHORT).show();
DownloadFromUrl(imgurl, i + ".jpg");
reviewImageLink = imgurl;// getString(R.string.ImageURI);
URL reviewImageURL;
fileName[i] = reviewImageLink.substring(reviewImageLink
.lastIndexOf("/") + 1);
// map.put("profile_image_url", fileName[i]);
map.put("logo", i + ".jpg");
list.setTextFilterEnabled(true);
mylist.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
/*final ListView lv = getListView();
lv.setTextFilterEnabled(true);*/
searchResult = new ArrayList<HashMap<String, String>>(mylist);
// adapter = new AdapterClass(Main.this, R.layout.main, mylist);
adapter = new AdapterClass(Main.this, R.layout.my_custom_layout, mylist);
// list.setAdapter(adapter);
setListAdapter(adapter);
edtSearch.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// get the text in the EditText
String searchString = edtSearch.getText().toString();
int textLength = searchString.length();
searchResult.clear();
for (int i = 0; i < mylist.size(); i++) {
String playerName = mylist.get(i).get("Name").toString();
if (textLength <= playerName.length()) {
// compare the String in EditText with Names in the
// ArrayList
if (searchString.equalsIgnoreCase(playerName.substring(
0, textLength)))
Toast.makeText(getApplicationContext(),
"Inside if of : " + playerName, 1000)
.show();
searchResult.add(mylist.get(i));
}
}
adapter.notifyDataSetChanged();
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
/*
* final ListView lv = getListView(); //lv.setTextFilterEnabled(true);
* lv.setOnItemClickListener(new OnItemClickListener() { public void
* onItemClick(AdapterView<?> parent, View view, int position, long id)
* {
*
* #SuppressWarnings("unchecked") HashMap<String, String> o =
* (HashMap<String, String>) lv .getItemAtPosition(position);
*
* } });
*/
}
public void DownloadFromUrl(String DownloadUrl, String fileName) {
try {
File dir = new File("/sdcard/pluto");
if (dir.exists() == false) {
dir.mkdirs();
}
URL url = new URL(DownloadUrl); // you can write here any link
File file = new File(dir, fileName);
long startTime = System.currentTimeMillis();
Log.d("DownloadManager", "download begining");
Log.d("DownloadManager", "download url:" + url);
Log.d("DownloadManager", "downloaded file name:" + fileName);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(5000);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
Log.d("DownloadManager",
"download ready in"
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " sec");
} catch (IOException e) {
Log.d("DownloadManager", "Error: " + e);
}
}
}
Please Help me.
You are not setting the adapter again in onTextChange. Add this inside onTextChange at the end:
setListAdapter(searchResult);
and remove
adapter.notifyDataSetChanged();

Scrolling is not perform in Listview in android

I have a problem that, I am adding listview in LinearLayout dynamically through code and set the EndlessAdapter into that, Data is shown correctly but we are unable to scroll from top to bottom in the list. I don't know why? please suggest me any solution regarding the same.
Code:
public void setValuesInCategoryChild(String url, final String filter, final String from, final String to) {
if (isOnline()) {
final ProgressDialog dialog = ProgressDialog.show(ResearchList.this, "Research List ", "Please wait... ", true);
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
// System.out.println("The id after Save:"+id.get(0).toString());
// catagory.addAll(keyword_vector1);
linear_Category_Child.setVisibility(View.GONE);
linear_Category_Child_Child.setVisibility(View.VISIBLE);
// tv_Child_Header.setText("Volvo");
tv_CategoryChildHeader.setText(from);
setHeaderImage(tv_CategoryChildHeader.getText().toString());
System.out.println("The size of Cat Display names:" + coll.getDisplayNames().size());
System.out.println("The size of Cat Images:" + coll.getImages().size());
System.out.println("The size of Cat price:" + coll.getPrice().size());
System.out.println("The size of Cat Year:" + coll.getYears().size());
System.out.println("The size of Cat Rating:" + coll.getRating().size());
System.out.println("The size of Cat Mpg:" + coll.getMpg().size());
setHeaderImage(tv_CategoryChildHeader.getText().toString());
if(coll.getDisplayNames().size()!=0) {
lvCategory = new ListView(ResearchList.this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
lvCategory.setLayoutParams(params);
// Adapter for MPG Search
demoAdapterCat = new DemoAdapterCat();
lvCategory.setAdapter(demoAdapterCat);
layout_ResearchList_BrandList.addView(lvCategory);
Utility.setListViewHeightBasedOnChildren(lvCategory);
}else {
/*lvCategory.invalidate();
lvCategory.setAdapter(null);*/
AlertDialog.Builder builder = new Builder(ResearchList.this);
builder.setTitle("Attention!");
builder.setMessage("No Data Available for the Particular Search.");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
builder.create().show();
}
/*Utility util = new Utility();
util.setListViewHeightBasedOnChildren(lvCategory);*/
dialog.dismiss();
}
};
final Thread checkUpdate = new Thread() {
public void run() {
try {
String sortEncode = URLEncoder.encode("mpg");
String filterEncode = URLEncoder.encode(filter);
String clientEncode = URLEncoder.encode("10030812");
String fromEncode = URLEncoder.encode(from);
String toEncode = URLEncoder.encode(to);
String catUrl = "/v1/vehicles/get-make-models.json?sort=" + sortEncode + "&filter=" + filterEncode + "&client-id=" + clientEncode + "&from=" + fromEncode;
genSig = new GetSignature(catUrl, "acura");
try {
signature = genSig.getUrlFromString();
} catch (InvalidKeyException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// jsonString =
// getJsonSring("http://api.highgearmedia.com/v1/vehicles/get-models.json?make=acura&client-id=10030812&signature=LWQbdAlJVxlXZ1VO2mfqAA==");
// String signatureEncode =
// URLEncoder.encode(signature);
String urlEncode = URLEncoder.encode(catUrl + "&signature=" + signature);
jsonString = getJsonSring("http://apibeta.highgearmedia.com" + catUrl + "&signature=" + signature);
System.out.println("The json category:===>" + jsonString);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JsonParse json = new JsonParse(jsonString);
json.parseCat();
LIST_SIZE = coll.getDisplayNames().size();
for (int i = 0; i <= BATCH_SIZE; i++) {
// countriesSub.add(COUNTRIES[i]);
countriesSubCat.add(coll.getDisplayNames().get(i));
imagesSubCat.add(coll.getImages().get(i));
YearSubCat1.add(coll.getYears().get(i));
YearSubCat2.add(coll.getYears().get(i + 1));
mpgSubCat1.add(coll.getMpg().get(i));
mpgSubCat2.add(coll.getMpg().get(i + 1));
priceSubCat1.add(coll.getPrice().get(i));
priceSubCat2.add(coll.getPrice().get(i + 1));
ratingSubCat1.add(coll.getRating().get(i));
ratingSubCat2.add(coll.getRating().get(i + 1));
}
setLastOffset(BATCH_SIZE);
handler.sendEmptyMessage(0);
}
};
checkUpdate.start();
} else {
AlertDialog.Builder builder = new Builder(ResearchList.this);
builder.setTitle("Attention!");
builder.setMessage("Network Connection unavailable.");
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
builder.create().show();
}
}
Layout:
<LinearLayout
android:id="#+id/linear_ResearchListCategoryChild_Child"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:visibility="gone" >
<RelativeLayout
android:id="#+id/linear_ResearchListCategoryChild_Child_HeaderBlock"
android:layout_width="fill_parent"
android:layout_height="40dip"
android:background="#drawable/catagory_bar"
android:orientation="horizontal" >
<TextView
android:id="#+id/tv_ResearchListCategoryChild_Child_Header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:text="Work in Progress"
android:textColor="#ffffff"
android:textStyle="bold" android:layout_marginLeft="60dip"/>
<ImageView
android:id="#+id/img_ResearchListCategory_ChildHeader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="10dip"
android:src="#drawable/up_arrow" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:src="#drawable/list_arrow_up" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/linear_ResearchListCategoryChild_Child_Header"
android:layout_width="fill_parent"
android:layout_height="40dip"
android:background="#drawable/nav_bg"
android:orientation="horizontal" >
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="5dip"
android:clickable="true"
android:text="Highest Rated"
android:textColor="#ffffff"
android:textStyle="bold" android:gravity="center"/>
<TextView
android:id="#+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView5"
android:layout_alignBottom="#+id/textView5"
android:layout_marginLeft="30dp"
android:layout_toRightOf="#+id/textView5"
android:clickable="true"
android:text="A-Z"
android:textColor="#ffffff"
android:textStyle="bold" android:gravity="center"/>
<TextView
android:id="#+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView6"
android:layout_alignBottom="#+id/textView6"
android:layout_marginLeft="40dp"
android:layout_toRightOf="#+id/textView6"
android:clickable="true"
android:text="Price"
android:textColor="#ffffff"
android:textStyle="bold" android:gravity="center"/>
<TextView
android:id="#+id/textView8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView7"
android:layout_alignBottom="#+id/textView7"
android:layout_alignParentRight="true"
android:layout_marginRight="14dp"
android:clickable="true"
android:text="MPG"
android:textColor="#ffffff"
android:textStyle="bold" android:gravity="center"/>
</RelativeLayout>
<!--
<RelativeLayout
android:id="#+id/relative_down_arrow"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="visible"
>
</RelativeLayout>
-->
<LinearLayout
android:id="#+id/linearArrowLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:visibility="visible">
<ImageView
android:id="#+id/Highly_rated"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="51dp"
android:src="#drawable/selector_arrow"
android:visibility="invisible" />
<ImageView
android:id="#+id/AZ_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="78dp"
android:src="#drawable/selector_arrow"
android:visibility="invisible" />
<ImageView
android:id="#+id/Price_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="59dp"
android:src="#drawable/selector_arrow"
android:visibility="invisible" />
<ImageView
android:id="#+id/MPG"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="55dp"
android:src="#drawable/selector_arrow"
android:visibility="invisible" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="12dip"
android:layout_marginRight="12dip" android:background="#ffffff" android:id="#+id/layout_ResearchList_BrandList">
</LinearLayout>
</LinearLayout>
DemoAdapterCat:
class DemoAdapterCat extends EndlessAdapter {
ImageLoader image = new ImageLoader(ResearchList.this);
private RotateAnimation rotate = null;
ArrayList<String> tempListNamesCat = new ArrayList<String>();
ArrayList<String> tempListImagesCat = new ArrayList<String>();
ArrayList<String> tempListYearCat1 = new ArrayList<String>();
ArrayList<String> tempListYearCat2 = new ArrayList<String>();
ArrayList<String> tempListmpgCat1 = new ArrayList<String>();
ArrayList<String> tempListmpgCat2 = new ArrayList<String>();
ArrayList<String> tempListpriceCat1 = new ArrayList<String>();
ArrayList<String> tempListpriceCat2 = new ArrayList<String>();
ArrayList<String> tempListRatingCat1 = new ArrayList<String>();
ArrayList<String> tempListRatingCat2 = new ArrayList<String>();
DemoAdapterCat() {
super(new CategoryListLazyAdapter(ResearchList.this,
countriesSubCat, imagesSubCat, YearSubCat1, YearSubCat2,
mpgSubCat1, mpgSubCat2, priceSubCat1, priceSubCat2,
ratingSubCat1, ratingSubCat2));
/*Utility util = new Utility();
util.setListViewHeightBasedOnChildren(lvCategory);*/
rotate = new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF,
0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
rotate.setDuration(600);
rotate.setRepeatMode(Animation.RESTART);
rotate.setRepeatCount(Animation.INFINITE);
}
/*
* #Override public int getCount() { return
* brandList.getDisplayNames().size(); //return count+=10; }
*/
#Override
protected View getPendingView(ViewGroup parent) {
row = getLayoutInflater().inflate(R.layout.categorylist, null);
child = row.findViewById(R.id.tv_CategoryItem_Name);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_MPG1);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_MPG2);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_Price1);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_Price2);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_Rating1);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_Rating2);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_Year1);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_Year2);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.linear_CategoryList_itemlayer1);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.linear_CategoryList_itemlayer2);
child.setVisibility(View.GONE);
/*
* child = row.findViewById(R.id.img_CategoryItem);
* child.setVisibility(View.GONE); child =
* row.findViewById(R.id.img_CategoryItem_Arrow);
* child.setVisibility(View.GONE);
*/
/*
* child = row.findViewById(R.id.linear_main_MPG);
* child.setVisibility(View.GONE);
*/
child = row.findViewById(R.id.throbber);
child.setVisibility(View.VISIBLE);
child.startAnimation(rotate);
return (row);
}
#Override
protected boolean cacheInBackground() {
//count += 10;
SystemClock.sleep(100000);
tempListNamesCat.clear();
tempListImagesCat.clear();
tempListmpgCat1.clear();
tempListmpgCat2.clear();
tempListpriceCat1.clear();
tempListpriceCat2.clear();
tempListYearCat1.clear();
tempListYearCat2.clear();
tempListRatingCat1.clear();
tempListRatingCat2.clear();
// countriesSubCat.clear();
// imagesSubCat.clear();
// YearSubCat1.clear();
// YearSubCat2.clear();
// mpgSubCat1.clear();
// mpgSubCat2.clear();
// priceSubCat1.clear();
// priceSubCat2.clear();
// ratingSubCat1.clear();
// ratingSubCat2.clear();
int lastOffset = getLastOffset();
if (lastOffset < LIST_SIZE) {
int limit = lastOffset + BATCH_SIZE;
for (int i = (lastOffset + 1); (i <= limit && i < LIST_SIZE); i++) {
tempListNamesCat.add(coll.getDisplayNames().get(i));
tempListImagesCat.add(coll.getImages().get(i));
tempListmpgCat1.add(coll.getMpg().get(i));
tempListmpgCat2.add(coll.getMpg().get(i + 1));
tempListpriceCat1.add(coll.getPrice().get(i));
tempListpriceCat2.add(coll.getPrice().get(i + 1));
tempListRatingCat1.add(coll.getRating().get(i));
tempListRatingCat2.add(coll.getRating().get(i + 1));
tempListYearCat1.add(coll.getYears().get(i));
tempListYearCat2.add(coll.getYears().get(i + 1));
}
setLastOffset(limit);
if (limit < LIST_SIZE) {
// return true;
return (getWrappedAdapter().getCount() < coll
.getDisplayNames().size());
} else {
return false;
}
} else {
return false;
}
}
#Override
protected void appendCachedData() {
#SuppressWarnings("unchecked")
// Activity activity = this;
// ArrayAdapter<String> arrAdapterNew =
// (ArrayAdapter<String>)getWrappedAdapter();
CategoryListLazyAdapter arrAdapterNewCategory = (CategoryListLazyAdapter) getWrappedAdapter();
// int listLen = tempList.size();
// int listLen = tempListNames.size();
countriesSubCat.addAll(tempListNamesCat);
imagesSubCat.addAll(tempListImagesCat);
mpgSubCat1.addAll(tempListmpgCat1);
mpgSubCat2.addAll(tempListmpgCat2);
priceSubCat1.addAll(tempListpriceCat1);
priceSubCat2.addAll(tempListpriceCat2);
ratingSubCat1.addAll(tempListRatingCat1);
ratingSubCat2.addAll(tempListRatingCat2);
YearSubCat1.addAll(tempListYearCat1);
YearSubCat2.addAll(tempListYearCat2);
arrAdapterNewCategory.notifyDataSetChanged();
/*Utility util = new Utility();
util.setListViewHeightBasedOnChildren(lvCategory);*/
/*
* for(int i=0; i<listLen; i++){ //
* arrAdapterNew.add(tempList.get(i)); }
*/
}
}
Thanks in adavance.
Try adding a ScrollView in the xml file.

Android code to record a video using remote IP camera which is accessed by using a url

Here are some links which tell about video recording:
How can I capture a video recording on Android?
https://github.com/churnlabs/android-ffmpeg-sample
and there are also many links which tell about video recording but got no any clue how to use the remote IP camera to record video.
By using different samples on stackoverflow I become able to take picture and save on sdcard but couldn't record video.
If any one has any idea or code along with required files I will be thankful.
For example the url I am using where the IP camera is available is given below:
http://trackfield.webcam.oregonstate.edu/axis-cgi/mjpg/video.cgi?resolution=800x600&amp%3bdummy=1333689998337
Here is the layout code:
<RelativeLayout
android:id="#+id/LinearLayout02"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/logo"
android:layout_alignParentTop="true"
android:layout_weight="1" >
<ImageButton
android:id="#+id/btnCam"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:src="#drawable/camera_icon" >
</ImageButton>
<ImageButton
android:id="#+id/btnVideo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:src="#drawable/camera_icon" >
</ImageButton>
</RelativeLayout>
<LinearLayout
android:id="#+id/LinearLayout03"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/LinearLayout01"
android:layout_below="#+id/LinearLayout02"
android:layout_weight="1" >
<RelativeLayout
android:id="#+id/RelativeLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#ffffff" >
<view
android:id="#+id/mv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
class="com.apps.GrahamConst.MjpegView" />
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_weight="1"
android:background="#drawable/navbar" >
<ImageButton
android:id="#+id/btnPrevious"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:layout_weight="1"
android:background="#null"
android:src="#drawable/previous" >
</ImageButton>
<ImageButton
android:id="#+id/btnMain"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:layout_weight="1"
android:background="#null"
android:src="#drawable/main" >
</ImageButton>
<ImageButton
android:id="#+id/btnNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:layout_weight="1"
android:background="#null"
android:src="#drawable/next" >
</ImageButton>
</LinearLayout>
</RelativeLayout>
Here is my Activity
public class CameraDetails2 extends Activity implements OnClickListener {
private MediaScannerConnection m_pScanner;
String drawable = null;
private MjpegView mv;
private ProgressDialog dialog;
private HashMap<String, String> item;
private int id = -1;
private WindowManager winMan;
boolean recording = false;
MediaRecorder recorder;
int bytearraysize = 0;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
winMan = (WindowManager) getApplicationContext().getSystemService(
Context.WINDOW_SERVICE);
if (winMan != null) {
int orientation = winMan.getDefaultDisplay().getOrientation();
if (orientation == 0) {
// Portrait
setContentView(R.layout.cameradetails);
} else if (orientation == 1) {
// Landscape
setContentView(R.layout.cameradetailsl);
}
}
Bundle b = getIntent().getExtras();
ImageButton b1 = (ImageButton) findViewById(R.id.btnNext);
b1.setOnClickListener(this);
ImageButton b2 = (ImageButton) findViewById(R.id.btnMain);
b2.setOnClickListener(this);
ImageButton b3 = (ImageButton) findViewById(R.id.btnPrevious);
b3.setOnClickListener(this);
ImageButton b4 = (ImageButton) findViewById(R.id.btnCam);
b4.setOnClickListener(this);
ImageButton b5 = (ImageButton) findViewById(R.id.btnVideo);
b5.setOnClickListener(this);
id = Integer.valueOf(b.get("id").toString());
item = listarrayadapter.cameraList.get(Integer.valueOf(id));
mv = (MjpegView) findViewById(R.id.mv);
try {
getVal(item.get("cameraLink"));
// getVal("http://trackfield.webcam.oregonstate.edu/axis-cgi/mjpg
/video.cgi?resolution=800x600&amp%3bdummy=1333689998337");
} catch (Exception e) {
e.printStackTrace();
mv.setBackgroundResource(R.drawable.offline);
}
}
#Override
protected void onResume() {
// if(recording)
// {
// getVal("http://trackfield.webcam.oregonstate.edu/axis-cgi/mjpg
/video.cgi?resolution=800x600&amp%3bdummy=1333689998337");
// }
super.onResume();
}
public void onPause() {
super.onPause();
dialog.dismiss();
mv.stopPlayback();
}
private void getVal(final String url) {
Log.i("URL===", url);
updateButtons();
dialog = ProgressDialog.show(this, null, null, true);
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
dialog.dismiss();
}
};
Thread checkUpdate = null;
checkUpdate = new Thread() {
public void run() {
mv.setSource(MjpegInputStream.read(url));
mv.setDisplayMode(MjpegView.SIZE_FULLSCREEN);
handler.sendEmptyMessage(0);
}
};
checkUpdate.start();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int btn = v.getId();
if (btn == R.id.btnMain) {
Intent intent = new Intent();
intent.setClass(CameraDetails2.this, CamerasList.class);
startActivity(intent);
finish();
}
if (btn == R.id.btnNext) {
id += 1;
Intent myintent = new Intent(CameraDetails2.this,
CameraDetails.class);
myintent.putExtra("id", id);
startActivity(myintent);
finish();
}
if (btn == R.id.btnPrevious) {
id -= 1;
Intent myintent = new Intent(CameraDetails2.this,
CameraDetails.class);
myintent.putExtra("id", id);
startActivity(myintent);
finish();
}
if (btn == R.id.btnCam) {
if (mv != null) {
Date dt = new Date();
int years = dt.getYear();
int month = dt.getMonth();
int day = dt.getDay();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
final String filename = years + "" + month + "" + day + ""
+ hours + "" + minutes + "" + seconds;
try {
Bitmap image = MjpegView.savebmp;
File SDCardRoot =
Environment.getExternalStorageDirectory();
FileOutputStream fileOutputStream = null;
fileOutputStream = new FileOutputStream(
SDCardRoot.toString() + "/" +
filename + ".jpg");
BufferedOutputStream bos = new
BufferedOutputStream(
fileOutputStream);
int quality = 95;
image.compress(CompressFormat.JPEG, quality, bos);
final String szFile = SDCardRoot.toString() + "/"
+ filename + ".jpg";
m_pScanner = new MediaScannerConnection(this,
new MediaScannerConnectionClient()
{
public void
onMediaScannerConnected() {
m_pScanner
.scanFile(szFile, null /* mimeType */);
}
public void
onScanCompleted(String path, Uri uri) {
if
(path.equals(szFile)) {
CameraDetails2.this
.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(
getApplicationContext(),
"Image Saved.",
Toast.LENGTH_LONG)
.show();
}
});
m_pScanner.disconnect();
}
}
});
m_pScanner.connect();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
if (btn == R.id.btnVideo) {
if (recording) {
// stop and save
recording = false;
MjpegInputStream.isrecording = false;
List<byte[]> bytelist = new ArrayList<byte[]>();
ArrayList<ByteArrayOutputStream> byteArrayStream =
MjpegInputStream.byteArrayStream;
for (int i = 0; i < byteArrayStream.size(); i++) {
byte[] templist
=byteArrayStream.get(i).toByteArray();
bytelist.add(templist);
}
for (int j = 0; j < bytelist.size(); j++) {
bytearraysize += bytelist.get(j).length;
}
byte[] totalbytes = new byte[bytearraysize];
int f = 0;
for (int j = 0; j < bytelist.size(); j++) {
for (int a = 0; a < bytelist.get(j).length; a++) {
totalbytes[f] = bytelist.get(j)[a];
f++;
}
}
Log.e("num of bytes", "" + totalbytes.length);
// Byte[] bytes = bytelist.toArray(new
//Byte[bytelist.size()]);
try {
writeToFile(totalbytes, "" +
System.currentTimeMillis());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
recording = true;
MjpegInputStream.isrecording = true;
// onResume();
// start recording
}
// recorder=new MediaRecorder();
// try {
// recorder.prepare();
// } catch (IllegalStateException e) {
// e.printStackTrace();
// finish();
// } catch (IOException e) {
// e.printStackTrace();
// finish();
// }
//
// //recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
// // recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
//
// //
// //
// // CamcorderProfile cpHigh = CamcorderProfile
// // .get(CamcorderProfile.QUALITY_HIGH);
// // recorder.setProfile(cpHigh);
// recorder.setVideoSource(mv.getId());
// recorder.setOutputFile("/sdcard/videocapture_example.mp4");
// recorder.setMaxDuration(50000); // 50 seconds
// recorder.setMaxFileSize(5000000); // Approximately 5 megabytes
}
}
public void writeToFile(byte[] bytes, String videoname) throws IOException {
try {
Log.e("num of bytes to be saved", "" + bytes.length);
String path = "/sdcard/" + videoname + ".mp4";
FileOutputStream stream = new FileOutputStream(path);
stream.write(bytes);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private void updateButtons() {
ImageButton btnNext = (ImageButton) findViewById(R.id.btnNext);
ImageButton btnPrevious = (ImageButton) findViewById(R.id.btnPrevious);
if (id == 0) {
btnPrevious.setEnabled(false);
} else {
btnPrevious.setEnabled(true);
}
if (id == listarrayadapter.cameraList.size() - 1) {
btnNext.setEnabled(false);
} else {
btnNext.setEnabled(true);
}
}
}

Categories

Resources