Android Bundle Concept to pass deta between activities - android

I am new to android here i am facing problem when i try to pass the retrived data from curser to bundle then i am not able to get the value of that variable.Below is my code please help me to come out from this situation.
Cursor cur3 = db3.rawQuery("SELECT * FROM " + TableName, null);
try {
db3 = this.openOrCreateDatabase("remoteid.db", MODE_PRIVATE, null);
if(cur3 != null )
{
if(cur3.moveToFirst())
{
do {
valueOfID = cur3.getString(cur3.getColumnIndex("PretestID"));
valuOfDate = cur3.getString(cur3.getColumnIndex("Date"));
textType = cur3.getString(cur3.getColumnIndex("txtVCT"));
valueOfDDLTS = cur3.getString(cur3.getColumnIndex("ddlTestingSession"));
valueOfReason = cur3.getString(cur3.getColumnIndex("txtReason"));
valueOfHowmany = cur3.getString(cur3.getColumnIndex("txthowmany"));
valueOftxtques1 = cur3.getString(cur3.getColumnIndex("txtques1"));
valueOfrblques2a = cur3.getString(cur3.getColumnIndex("rblques2a"));
valueOfrblques2b = cur3.getString(cur3.getColumnIndex("rblques2b"));
valueOfrblques3 = cur3.getString(cur3.getColumnIndex("rblques3"));
valueOftxtques4 = cur3.getString(cur3.getColumnIndex("txtques4"));
valueOfrblques5 = cur3.getString(cur3.getColumnIndex("rblques5"));
valueOfrblques6 = cur3.getString(cur3.getColumnIndex("rblques6"));
valueOfrblques7 = cur3.getString(cur3.getColumnIndex("rblques7"));
valueOfrblques8 = cur3.getString(cur3.getColumnIndex("rblques8"));
valueOfrblques9 = cur3.getString(cur3.getColumnIndex("rblques9"));
valueOfddlsick = cur3.getString(cur3.getColumnIndex("ddlsick"));
valueOftxtques11 = cur3.getString(cur3.getColumnIndex("txtques11"));
valueOfrblques12 = cur3.getString(cur3.getColumnIndex("rblques12"));
valueOftxtques13 = cur3.getString(cur3.getColumnIndex("txtques13"));
valueOftxtques14 = cur3.getString(cur3.getColumnIndex("txtques14"));
valueOfrblques15 = cur3.getString(cur3.getColumnIndex("rblques15"));
valueOfrblques16 = cur3.getString(cur3.getColumnIndex("rblques16"));
valueOfrblques17 = cur3.getString(cur3.getColumnIndex("rblques17"));
valueOftxtques18 = cur3.getString(cur3.getColumnIndex("txtques18"));
//Toast.makeText(getApplicationContext(), valueOftxtques18, Toast.LENGTH_SHORT).show();
}while (cur3.moveToNext());
}
}
}
catch(Exception e) {
Log.e("Error", "Error", e);
} finally {
if (db3 != null)
db3.close();
}
cur3.close();
arrayadapter11 = new simpleefficientadapter(Screening.this,prtestData);
arrayadapter22 = new simpleefficientadapter(Screening.this,screeningData);
arrayadapter33 = new simpleefficientadapter(Screening.this,postData);
mylist1.setAdapter(arrayadapter11);
mylist1.setOnItemClickListener(this);
mylist2.setAdapter(arrayadapter22);
mylist2.setOnItemClickListener(this);
mylist3.setAdapter(arrayadapter33);
mylist3.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Intent intent;
switch (arg0.getId()) {
case R.id.prescreenlist:
intent = new Intent(getApplicationContext(), NewScreening.class);
Bundle bundle = new Bundle();
bundle.putString("DateValue", valuOfDate);
bundle.putString("TT", textType);
bundle.putString("idValue", valueOfID);
bundle.putString("ddltsValue", valueOfDDLTS);
bundle.putString("reasonValue", valueOfReason);
bundle.putString("howmanyValue", valueOfHowmany);
bundle.putString("textqus1Value", valueOftxtques1);
bundle.putString("textqus2aValue", valueOfrblques2a);
bundle.putString("textqus2bValue", valueOfrblques2b);
bundle.putString("rbqs3Value", valueOfrblques3);
bundle.putString("rbqs4Value", valueOftxtques4);
bundle.putString("rbqs5Value", valueOfrblques5);
bundle.putString("rbqs6Value", valueOfrblques6);
bundle.putString("rbqs7Value", valueOfrblques7);
bundle.putString("rbqs8Value", valueOfrblques8);
bundle.putString("rbqs9Value", valueOfrblques9);
bundle.putString("ddlsValue", valueOfddlsick);
bundle.putString("tq11Value", valueOftxtques11);
bundle.putString("tq12Value", valueOfrblques12);
bundle.putString("tq13Value", valueOftxtques13);
bundle.putString("tq14Value", valueOftxtques14);
bundle.putString("rbqs15Value", valueOfrblques15);
bundle.putString("rbqs16Value", valueOfrblques16);
bundle.putString("rbqs17Value", valueOfrblques17);
bundle.putString("rbqs18Value", valueOftxtques18);
intent.putExtras(bundle);
startActivityForResult(intent, 1);
setResult(1,intent);
break;

A wiser move, might be passing the id of that database row to the next Activity.
And your code is incomplete, but it looks like only the last row's data will ever be passed to the next activity.
Also, it might be mildly more efficient and clear if you just putExtra directly into the intent instead of the intermediary Bundle.
Good practices said to include the package name as a prefix in the extra names.

Related

Open/Close SQL Database on the same thread

I'm developing a recipe book and I'm implementing this method to insert my Recipe in the Database. In the for cycle I get the ingredient's name and quantity from multiples EditText, saving each of them in an Ingredient.class instance (newIngredient). Then I insert the instance into the DB and add it to an ArrayList. The followings "if conditions" are for the title, time and other Recipe's attributes. Finally, I also insert Recipe and Tag instances in the relatives DB's tables and I close DB.
public void saveRecipe() {
dbHelper = new DatabaseHelper(context);
// creating new recipe from user input
Ingredient newIngredient;
String title, childIngredient, instruction, tag;
int target, time, childQuantity, calories;
int countIngredients = parentIngredientLayout.getChildCount();
int countTags = chipGroup.getChildCount();
ArrayList<Ingredient> ingredients = null;
ArrayList<Tag> tags = null;
View childViewIng = null;
EditText childTextViewI = null;
EditText childTextViewQ = null;
// ingredients fields settings
for (int d=0; d<countIngredients; d++) {
childViewIng = parentIngredientLayout.getChildAt(d);
childTextViewI = childViewIng.findViewById(R.id.ingredientsField);
childTextViewQ = childViewIng.findViewById(R.id.quantityField);
childIngredient = childTextViewI.getText().toString();
childQuantity = Integer.parseInt(childTextViewQ.getText().toString());
newIngredient = new Ingredient(childIngredient, childQuantity);
dbHelper.insertIngredient(newIngredient);
ingredients.add(newIngredient);
}
//recipe fields settings
if (photoPath1 == null)
photoPath1 = "";
if (photoPath2 == null)
photoPath2 = "";
if (photoPath3 == null)
photoPath3 = "";
if (titleText.getText().toString().isEmpty()) {
title = "";
} else {
title = titleText.getText().toString();
}
if (targetNumber.getText().toString().isEmpty()) {
target = 0;
} else {
target = Integer.parseInt(targetNumber.getText().toString());
}
if (timeNumber.getText().toString().isEmpty()) {
time = 0;
} else {
time = Integer.parseInt(timeNumber.getText().toString());
}
if (instructionText.getText().toString().isEmpty()) {
instruction = "";
} else {
instruction = instructionText.getText().toString();
}
if (caloriesNumber.getText().toString().isEmpty()) {
calories = 0;
} else {
calories = Integer.parseInt(caloriesNumber.getText().toString());
}
if (tagName.getText().toString().isEmpty()) {
tag = "";
} else {
tag = tagName.getText().toString();
}
Recipe newRecipe = new Recipe(title, photoPath1, photoPath2, photoPath3, instruction, target, time, calories, ingredients);
Tag newTag = new Tag(tag);
dbHelper.insertRecipe(newRecipe);
dbHelper.insertTag(newTag);
dbHelper.close(); }
I found out by debugging that in this case is inserted only the first ingredient. I tried to move the FOR until the end of code, but in that case, are inserted both recipe and tag and always only the first ingredient. I think the problem is relative to the opening/closing of the DB. Can somebody help me?
Ingredient constructor:
public Ingredient(String ingredient_name, int quantity) {
this.ingredient_name = ingredient_name;
this.quantity = quantity;
}
dbHelper.insertIngredient(newIngredient) method:
public boolean insertIngredient(Ingredient ingredient) {
db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(INGREDIENT_NAME, ingredient.getIngredient_name());
contentValues.put(QUANTITY, ingredient.getQuantity());
contentValues.put(KEY_CREATED_AT, time.getTime().toString());
long result = db.insert(TBL_INGREDIENTS, null, contentValues);
//db.close();
Log.e(TAG, "Ingredient inserted!");
if (result == -1) {
return false;
} else {
return true;
}
}
Ok, thanks to your comment we got the problem :)
You are calling .add(newIngredient) on a list that you initialized with ArrayList<Ingredient> ingredients = null;
Change it to
ArrayList<Ingredient> ingredients = new ArrayList<Ingredient>();
and it will work :)
Good luck!

How do i fix this error, System.NotSupportedException: Could not activate JNI Handle 0x7fec3e5620

I have tried searching for the error but i can't seem to link the results i find to my application.
Here is the error i get whenever i run my program.
Unhandled Exception:
System.NotSupportedException: Could not activate JNI Handle
0x7fec3e5620 (key_handle 0xe1ccda9) of Java
type 'md5ca0dbb1ec41706184e899fc3d5b0057e/MainActivity'
as managed type 'PowerCellShipping3.MainActivity'. occurred
Here is my c# code. I am unsure what is actually causing the error as i have never come across this error(obviously.)
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
scan = FindViewById<Button>(Resource.Id.btnScan);
lbviewScan = FindViewById<ListView>(Resource.Id.lvbScanned);
lbviewReject = FindViewById<ListView>(Resource.Id.lbRejected);
tvscanned = FindViewById<TextView>(Resource.Id.textView4);
tvreject = FindViewById<TextView>(Resource.Id.textView5);
etLot = FindViewById<EditText>(Resource.Id.etLotNumber);
scan.Click += delegate {
//Call Your Method When User Clicks The Button
btnClick();
};
}
/**************************************************************************************************************************************************************/
public class ToDoTasks
{
[PrimaryKey, AutoIncrement, Column("#Lot_Number")]
public int Id { get; set; }
[MaxLength(100)]
public string Task { get; set; }
}
public List<string> GetData()
{
var db = new SQLiteConnection("Data Source = obdbnsql3; Persist Security Info=True;User ID = sa" + "Password=P0w3r1T");
List<string> data = new List<string>();
foreach (var item in db.Table<ToDoTasks>())
{
var objectItem = item.Task.ToString();
data.Add(objectItem);
}
return data;
}
/***************************************************************************************************************************************************************/
public void btnClick()
{
sql1 = "update [Otto_Internal_Apps].[dbo].[Shipping_Detail] set [Box_Scanned] = 1, [Shipment_Scan_Date] = GETDATE(), [Box_Rejected] = 0 " +
"where [Lot_No] = #Lot_Number and ([Box_Rejected] != 1 or [Box_Rejected] is null)";
SQLiteCommand sqlCommand = new SQLiteCommand(connection);
sqlCommand.CommandText.Replace(sql1,sql1);
string attempt = sql1;
int iCount = Convert.ToInt32(attempt);
sqlCommand.CommandText.Remove(iCount,iCount);
/********************************************************************************************************************************/
string attempt2 = "#Lot_Number";
int iCount2 = Convert.ToInt32(attempt2);
//sqlCommand.Parameters.AddWithValue("#Lot_number", etLot.Text);
sqlCommand.CommandText.Insert(iCount2, etLot.Text);
/********************************************************************************************************************************/
try
{ // Execute the query and return the rows affected
sql2 = "select top 1 * from [Otto_Internal_Apps].[dbo].[Shipping_Detail] where [Lot_No] = #Lot_Number and [Box_Rejected] = 1";
int iRowsAffected = sqlCommand.ExecuteNonQuery();
// if the rows affected is zero then the lot no. does not exist and must be inserted as a rejected scan
if (iRowsAffected == 0)
{
sqlCommand.CommandText = sql2;
sql3 = "INSERT INTO [Otto_Internal_Apps].[dbo].[Shipping_Detail] ([Lot_No],[Box_Rejected]) VALUES(#Lot_Number, 1) ";
//lbviewScan.Load(sqlCommand.ExecuteQuery);
var items = GetData();
var listView = FindViewById<ListView>(Resource.Id.lvbScanned);
listView.Adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, items);
if (lbviewScan.Count == 0)
{
sqlCommand.CommandText = sql3;
string attempt3 = sql3;
int iCount3 = Convert.ToInt32(attempt3);
sqlCommand.CommandText.Remove(iCount3, iCount3);
string attempt4 = "#Lot_Number";
int iCount4 = Convert.ToInt32(attempt4);
sqlCommand.CommandText.Insert(iCount4, etLot.Text);
sqlCommand.ExecuteNonQuery();
}
//int iItemFound = lbviewReject.Items.IndexOf(etLot.Text);
int iItemFound = itemList.IndexOf(etLot.Text);
if (iItemFound == -1)
{
//lbviewReject.Items.Add(etLot.Text);
itemList.Add(etLot.Text);
}
}
else
{
//int iItemFound = lbviewScan.Items.IndexOf(etLot.Text);
int iItemFound = itemList.IndexOf(etLot.Text);
if (iItemFound == -1)
{
//lbviewScan.Items.Add(etLot.Text);
itemList.Add(etLot.Text);
}
Console.Beep(800, 200);
}
}
catch (SQLException sqle)
{
Toast.MakeText(ApplicationContext, sqle.Message, ToastLength.Long).Show();
Console.Beep(2000, 1600);
return;
}
The other posts that I saw on the Xamarin site seemed to be similar errors but like i said before, I still can't find a solution.
I think that the error could be caused due to one of the listboxes but i am unsure about that.
Any help would be greatly appreciated. Thanks

Why is intent.getStringExtra always null?

I've looked and looked. Tried many things but nothing returns the data (regardless that it's present)
The information is being passed as: -> NOTE I posted wrong snippet, see below
userLists.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
Intent DisplayItems = new Intent(getApplicationContext(), Items.class);
Map<String,String> storeMap = lst.get(pos);
DisplayItems.putExtra("id", storeMap.get("id"));
startActivityForResult(DisplayItems, 1);
}
});
Received in onCreate:
groupIntent = getIntent();
if(groupIntent.hasExtra("groupid")) {
groupId = groupIntent.getStringExtra("groupid");
resultCode = 2;
}
groupId always returns null. In the debug groupIntent -> mExtras -> mMap -> value[0] = 5c00a086d45213.24138362 is displayed. All other classes pass and receive the intent as intended..
EDIT: My bad.. This is what actually inserts the extra
public void btnCreateList_Click(View view) {
Intent createList = new Intent(context, CreateList.class);
if(groupId!=null) {
String grp = groupId;
createList.putExtra("groupid", grp);
}
startActivityForResult(createList, 1);
}
The code should be like below:
groupIntent = getIntent();
if(groupIntent.hasExtra("id")) {
groupId = groupIntent.getStringExtra("id");
resultCode = 2;
}

Variable Stays Null

I'm trying to pass a String between activities, From YtAdapter to Favorites.
YtAdapter:
mHolder.mVideoFavorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//////////////////////////////////////////////////////////////
// Need to send SearchResult result from here to favorites //
////////////////////////////////////////////////////////////
AppUtils.showToast(result.getSnippet().getTitle() + " Was added to favorites.");
Intent intent = new Intent(mActivity,Favorites.class);
String vidId,vidTitle,vidThumbnail;
vidId = result.getId().getVideoId(); //Video ID
vidTitle = result.getSnippet().getTitle(); //Video Title
vidThumbnail = result.getSnippet().getThumbnails().getMedium().getUrl(); //Video Thumbnail
intent.putExtra("id",vidId);
intent.putExtra("title",vidTitle);
intent.putExtra("thumbnail",vidThumbnail);
}
});
And try to get it in Favorites:
/*Getting video information from YtAdapter*/
vidID = getIntent().getStringExtra("id"); <--- Stays null
vidTitle = getIntent().getStringExtra("title"); <--- Stays null
vidThumbnail = getIntent().getStringExtra("thumbnail"); <--- Stays null
I'm accessing Favorties from 3rd activity, not straight from YtAdapter.
try this in your main class:
Intent i = new Intent(ListViewActivity.this, EditContact.class);
Bundle bundle = new Bundle();
bundle.putInt("index", itemId);
bundle.putBoolean("AddContact", false);
i.putExtras(bundle);
startActivity(i);
and you can get your data in the other class like this:
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
Int index = bundle.getInt("index");
Boolean bool = bundle.getBoolean("AddContact");
if (bool ) {
setTitle("Add Contact");
} else {
setTitle("Edit Contact");
}
I hope it will help.
you can force all of your parameter be a string value:
intent.putExtra("id",vidId +"");
intent.putExtra("title",vidTitle+"");
intent.putExtra("thumbnail",vidThumbnail+"");
probally they aren't and you are getting with "getStringExtra".
but the better options is you use te correct "getter" of extra.
---Edit---
you can check in your activity the keys and values this way:
for(String key : getIntent().getExtras().keySet()){
Log.d("TEST", "key: " + key);
Log.d("TEST", "value: " + getIntent().getExtras().get(key));
}

How to refresh list View in android?

I am using .net web services. I am trying to get list in ListView. Right now it is showing me the first list, but when I am trying to get it again using the same method it is giving me a response in log but not displaying in list.
I have used mAdapter.notifyDataSetChanged(); in my Adapter but it's not working. Please help. thanks
My code:
Intent mIntent = getIntent();
mIntent.getStringExtra("folder_name");
Id = mIntent.getStringExtra("folder_ID");
mIntent.getStringExtra("item_parent");
User_ID = mIntent.getStringExtra("User_ID");
subfolderTreedata();
}
public void subfolderTreedata() {
try {
--------
--------
-------- //some code here...
SoapObject SubfolderResponse = (SoapObject)envelope.getResponse();
Log.i("SubFolders", SubfolderResponse.toString());
String File_Ext=" ";
subfoldersitem = new String[SubfolderResponse.getPropertyCount()];
System.out.println(subfoldersitem.length);
for(int i=0; i < SubfolderResponse.getPropertyCount(); i++) {
SoapObject SingleSubFolder = (SoapObject)SubfolderResponse.getProperty(i);
subfoldersitem[0] = SingleSubFolder.getProperty(1).toString();
subfoldersitem[1] = SingleSubFolder.getProperty(0).toString();
subfoldersitem[2] = SingleSubFolder.getProperty(3).toString();
if(KEY_SUBJECTTYPE.equalsIgnoreCase("Folder")) {
item = new FolderList(Folderimages[0], subfoldersitem[0], subfoldersitem[1], subfoldersitem[2]);
Subfolderdata.add(item);
} else{
StringTokenizer tokens = new StringTokenizer(Name, ".");
#SuppressWarnings("unused")
String first_string = tokens.nextToken();
File_Ext = tokens.nextToken();
if(File_Ext.equalsIgnoreCase("TIF")) {
item = new FolderList(TIFimages[0], subfoldersitem[0], subfoldersitem[1], subfoldersitem[2]);
Subfolderdata.add(item);
} else {
item = new FolderList(noImage[0], subfoldersitem[0], subfoldersitem[1], subfoldersitem[2]);
Subfolderdata.add(item); }
}
}
subfolderslistview = (ListView)findViewById(R.id.subfolderslistview);
mAdapter = new LazyAdapter(this, R.layout.jpg_row, Subfolderdata);
subfolderslistview.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
subfolderslistview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
LazyAdapter ca = (LazyAdapter)parent.getAdapter();
FolderList item_name = (FolderList)ca.getItem(position);
FolderList DocumentID = (FolderList)ca.getItem(position);
FolderList type = (FolderList)ca.getItem(position);
Intent mIntent = new Intent();
mIntent.putExtra("item_name", item_name.folder_name);
mIntent.putExtra("item_id", DocumentID.ID);
mIntent.putExtra("item_type", type.type);
mIntent.getStringExtra("item_name");
String Type = mIntent.getStringExtra("item_type");
Log.i("Type", Type);
if(Type.equalsIgnoreCase("Folder")){
Id = mIntent.getStringExtra("item_id");
mAdapter.notifyDataSetChanged();
subfolderTreedata();
} else {
Intent i = new Intent(getApplicationContext(), Display_image.class);
i.putExtra("item_name", item_name.folder_name);
i.putExtra("ID", DocumentID.ID);
i.putExtra("item_type", type.type);
i.putExtra("User_ID",User_ID);
i.getStringExtra("item_name");
Id = i.getStringExtra("ID");
i.getStringExtra("item_type");
Log.i("id", Id);
startActivity(i);
}
}
});
public void list() {
mAdapter = new LazyAdapter(this, R.layout.jpg_row, Subfolderdata);
subfolderslistview.setAdapter(mAdapter);
}
Use like this list();.
Call this method from Where do you want.

Categories

Resources