How to put the selected number into next edittext? - android

Good day!
i am quite new in programming and i am trying to make a simple android app. i have here 2 edittext and 2 buttons inside my activity and what i want them to do is get the number of prefered contacts to text and the 1st edittext and 1st button succeeded but my problem is the button 2 also put the number on the 1st edittext that is supposed to put in 2nd edittext any idea?
this is my code..
public class SA extends Activity {
EditText con1;
EditText con2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_s);
con1 = (EditText) findViewById(R.id.cnum1);
con2 = (EditText) findViewById(R.id.cnum2);
((Button)findViewById(R.id.btnSelectContact1)).setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
// user BoD suggests using Intent.ACTION_PICK instead of .ACTION_GET_CONTENT to avoid the chooser
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// BoD con't: CONTENT_TYPE instead of CONTENT_ITEM_TYPE
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, 1);
}
});
((Button)findViewById(R.id.btnSelectContact2)).setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v2) {
// user BoD suggests using Intent.ACTION_PICK instead of .ACTION_GET_CONTENT to avoid the chooser
Intent intent2 = new Intent(Intent.ACTION_GET_CONTENT);
// BoD con't: CONTENT_TYPE instead of CONTENT_ITEM_TYPE
intent2.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent2, 1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,},
null, null, null);
if (c != null && c.moveToFirst()) {
String number = c.getString(0);
showSelectedNumber(number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
protected void onActivityResult2(int requestCode2, int resultCode2, Intent data2) {
if (data2 != null) {
Uri uri2 = data2.getData();
if (uri2 != null) {
Cursor c2 = null;
try {
c2 = getContentResolver().query(uri2, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,},
null, null, null);
if (c2 != null && c2.moveToNext()) {
String number2 = c2.getString(0);
showSelectedNumber(number2);
}
} finally {
if (c2 != null) {
c2.close();
}
}
}
}
}
public void showSelectedNumber(String number) {
con1.setText(number);
}
public void showSelectedNumber2(String number2) {
con2.setText(number2);
}

No need of onActivityResult2() because startActivityForResult() gives you result back in onActivityResult() method.
So now your question would be, how you can manage different requests? Well, that you can do by passing different request code while calling startActivityForResult().
For example:
startActivityForResult(intent, 1); // first request
startActivityForResult(intent, 2); // second request
// you can pass any random number as a request code
Now you just need to perform the operations according to the request code received back in onActivityResult() method.
For example:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
if(requestCode == 1) {
...
...
} else if (requestCode == 2) {
...
...
}
}
}

Related

App crashing on buttonclick how can I solved it android studio

Here is the code:
button.setOnClickListener(new View.OnClickListener() {
#Override public void onClick (View view){
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
}
}); return view;}
public void but(View v) {
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case RESULT_PICK_CONTACT:
contactPicked(data);
break;
}
} else {
Log.e("MainActivity", "Failed to pick contact");
}
}
private void contactPicked(Intent data) {
Cursor cursor = null;
try {
String phoneNo = null;
String name = null;
Uri uri = data.getData();
cursor = getActivity().getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int phoneIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int nameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
phoneNo = cursor.getString(phoneIndex);
name = cursor.getString(nameIndex);
if (phoneNo.startsWith("+")) {
if (phoneNo.length() == 13) {
String str_getMOBILE = phoneNo.substring(4);
editText.setText(("0") + str_getMOBILE);
}
if (phoneNo.length() == 16) {
String str_getMOBILE = phoneNo.substring(4);
editText.setText(("0") + str_getMOBILE);
}
} else {
editText.setText(phoneNo);
}
} catch (Exception e) {
e.printStackTrace();
}
}
You may be facing any of the following scenarios that led to the crash :
Your button is not declared and initiated properly in the onCreate() method of your main class. So please check if you have the below code in your onCreate() method :
Button button = (Button) findViewById(R.id.button);
Your app reads contacts from the user device I believe. In that case, please check if you have necessary permission to read contacts. For that, just check if the below line is included in the AndroidManifest.xml file :
<uses-permission android:name="android.permission.READ_CONTACTS" />
Check if you have permission to call the appropriate intent.
Your logcat trace will contain the exact line of code that led to the crash and the error code. So if you paste the logcat info here, you can get help.

Update Android Image Bitmap to SQLite Blob

I am trying to figure out where I went wrong either coding or logical flaw, I created a Recipe App that takes a couple of strings and an image, all data get saved into database and on the main screen I get a list of recipes from database.
Main Screen
Add / Edit Screen
Creating or Adding new Data is working as expected, all data get saved. The problem is everything can be updated except for the Image once it has been saved any second attempt doesn't seem to affect the image, the image remains the same.
The core principle is to set data to the views (When user start the activity onCreate or resume the activity onResume) and get data from the views (When user leaves onPause and onSaveInstanceState just incase an update was made)
Code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_edit);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
enableEdit();
fab.hide();
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
recipeDAOImp = new RecipeDAOImp(this);
recipeDAOImp.open();
findViews();
rowId = (savedInstanceState == null) ? null :
(Long) savedInstanceState.getSerializable(RecipeDAOImp.KEY_ID);
if (rowId == null) {
Bundle extras = getIntent().getExtras();
rowId = extras != null ? extras.getLong(RecipeDAOImp.KEY_ID)
: null;
}
populateData();
disableEdit();
}
private void findViews() {
// Finds Views and Set onClick to imageButton
}
private void disableEdit() {
// Disable Views
}
private void enableEdit() {
// Enables Views
}
private void populateData() {
// If rowId is available then user is trying to Edit Recipe
if (rowId != null) {
setTitle("Edit Recipe");
Recipe recipe = new Recipe(rowId);
Cursor cursor = recipeDAOImp.getRecipe(recipe);
startManagingCursor(cursor);
title.setText(cursor.getString(
cursor.getColumnIndexOrThrow(RecipeDAOImp.KEY_TITLE)));
ingredients.setText(cursor.getString(
cursor.getColumnIndexOrThrow(RecipeDAOImp.KEY_INGREDIENTS)));
steps.setText(cursor.getString(
cursor.getColumnIndexOrThrow(RecipeDAOImp.KEY_STEPS)));
category.setText(cursor.getString(
cursor.getColumnIndexOrThrow(RecipeDAOImp.KEY_CATEGORY)));
BitmapDrawable bitmapDrawable = new BitmapDrawable(getResources(), DbBitmapUtility.getImage(cursor.getBlob(
cursor.getColumnIndexOrThrow(RecipeDAOImp.KEY_IMAGE))));
image.setBackground(bitmapDrawable);
// Else user is Adding a new Recipe
} else {
fab.hide();
setTitle("Add Recipe");
enableEdit();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveState();
outState.putSerializable(RecipeDAOImp.KEY_ID, rowId);
}
#Override
protected void onPause() {
super.onPause();
saveState();
}
#Override
protected void onResume() {
super.onResume();
populateData();
}
private void saveState() {
// Get the values from the views
String titleString = title.getText().toString();
String ingredientString = ingredients.getText().toString();
String stepsString = steps.getText().toString();
String categoryString = category.getText().toString();
// Get the image from imageButton
Drawable drawable = image.getBackground();
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
byte[] imageData = DbBitmapUtility.getBytes(bitmap);
// Just to clarify image is never null as the backround is a camre image
if (titleString.equals(null) || "".equals(titleString) || ingredientString.equals(null) || "".equals(ingredientString) || stepsString.equals(null) || "".equals(stepsString) || categoryString.equals(null) || "".equals(categoryString) || imageData.equals(null) || "".equals(imageData)) {
Toast.makeText(this, "No Data Saved", Toast.LENGTH_SHORT).show();
} else {
Recipe recipe = new Recipe(titleString, ingredientString, stepsString, categoryString, imageData);
// If rowId is not Available then user is Creating a new Recipe
if (rowId == null) {
long id = recipeDAOImp.createRecipe(recipe);
if (id > 0) {
rowId = id;
}
} else {
recipe.setId(rowId);
recipeDAOImp.updateRecipe(recipe);
}
}
}
#Override
public void onClick(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
// Set the imageButton
BitmapDrawable bitmapDrawable = new BitmapDrawable(getResources(), imageBitmap);
image.setBackground(bitmapDrawable);
}
}
}
DAO
#Override
public boolean updateRecipe(Recipe recipe) {
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_TITLE, recipe.getTitle());
contentValues.put(KEY_INGREDIENTS, recipe.getIngredients());
contentValues.put(KEY_STEPS, recipe.getSteps());
contentValues.put(KEY_CATEGORY, recipe.getCategory());
contentValues.put(KEY_IMAGE, recipe.getImage());
return sqLiteDatabase.update(DATABASE_TABLE, contentValues, KEY_ID + "=" + recipe.getId(), null) > 0;
}
What could be the problem that I can update string data but I can't really update the image once its saved?
After much research and testing, the problem was simply the image button can not be reset.
image.setBackground(bitmapDrawable);
This method above seems not to work for an update, my quick fix was simply to leave the code as it is and simply add a detection onActivityResult to determine if its actually an update then, add the byte data to database directly, rather than updating the image button and then recreate() the Activity, expensive procedure but not costly for a simple app.
if (rowId != null) {
...
recipe.setImage(DbBitmapUtility.getBytes(imageBitmap));
recipeDAOImp.updateRecipe(recipe);
recreate();
}
All Working as expected.
My guess is that the problem is in your DAO code. I have a similar setup (sqlite table with text and blob columns, both get updated), so I know that what you're trying to do is possible.

Unable to save multiple contacts by different buttons

I want to fetch contacts from my phonebook and save the name and number of a contact. I want to save 3 contacts. For which, 3 EditTexts And respective buttons are there. On button click user is directed to contacts where user can select desired contact. But, I am unable to implement Contact-fetch function for all 3 Edit Texts.
When i implement this with one contact only, code works fine. But, how can this be implemented in the case of multiple contacts.
Contact.java
package com.kamal.sos10;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.content.Intent;
import android.widget.Toast;
public class Contact extends AppCompatActivity {
EditText msg,editText2,editText3,editText4;
Button con1,con2,con3;
static final int PICK_CONTACT = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact);
msg=(EditText)findViewById(R.id.msg);
editText2=(EditText)findViewById(R.id.editText2);
editText3=(EditText)findViewById(R.id.editText3);
editText4=(EditText)findViewById(R.id.editText4);
con1=(Button)findViewById(R.id.con1);
con2=(Button)findViewById(R.id.con2);
con3=(Button)findViewById(R.id.con3);
con1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.putExtra("extra_text1", "1");
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
if (intent.resolveActivity(Contact.this.getPackageManager()) != null) {
startActivityForResult(intent, PICK_CONTACT);
}
}
});
con2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.putExtra("extra_text2", "2");
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
if (intent.resolveActivity(Contact.this.getPackageManager()) != null) {
startActivityForResult(intent, PICK_CONTACT);
}
}
});
con3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.putExtra("extra_text3", "3");
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
if (intent.resolveActivity(Contact.this.getPackageManager()) != null) {
startActivityForResult(intent, PICK_CONTACT);
}
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String text1 = getIntent().getStringExtra("extra_text1");
Toast.makeText(Contact.this,text1,Toast.LENGTH_SHORT).show();
if (requestCode == PICK_CONTACT) {
if (resultCode == this.RESULT_OK) {
contactPicked(data);
}
}
}
private void contactPicked(Intent data) {
ContentResolver cr = this.getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
cur.moveToFirst();
try {
// getData() method will have the Content Uri of the selected contact
Uri uri = data.getData();
//Query the content uri
cur = this.getContentResolver().query(uri, null, null, null, null);
cur.moveToFirst();
// column index of the contact ID
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
// column index of the contact name
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// column index of the phone number
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
String phone = pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)).replaceAll(" ", "");
/*String text1 = getIntent().getStringExtra("extra_text1");
Toast.makeText(Contact.this,text1,Toast.LENGTH_SHORT).show();
if (text1.equals("1")) {
editText2.setText(phone);
}
String text2 = getIntent().getStringExtra("extra_text2");
if (text2 == "2") {
editText3.setText(phone);
}
String text3 = getIntent().getStringExtra("extra_text3");
if (text3 == "3") {
editText4.setText(phone);
*/}
pCur.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
You have used PICK_CONTACT = 1 for all three occurrences of startActivityForResult
startActivityForResult(intent, PICK_CONTACT);
Give different value for each occurrence of startActivityForResult like below:
con1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.putExtra("extra_text", "1");
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
if (intent.resolveActivity(Contact.this.getPackageManager()) != null) {
startActivityForResult(intent, 1);
}
}
});
con2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.putExtra("extra_text", "2");
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
if (intent.resolveActivity(Contact.this.getPackageManager()) != null) {
startActivityForResult(intent, 2);
}
}
});
con3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.putExtra("extra_text", "3");
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
if (intent.resolveActivity(Contact.this.getPackageManager()) != null) {
startActivityForResult(intent, 3);
}
}
});
Now in your onActivityResult change the below code:
if (requestCode == PICK_CONTACT) {
if (resultCode == this.RESULT_OK) {
contactPicked(data);
}
}
to this:
if (requestCode == 1 || requestCode == 2 || requestCode == 3) {
if (resultCode == this.RESULT_OK) {
contactPicked(data);
}
}
Now to print phone number in edittext box add the below code to contactPicked(Intent data):
String text = data.getStringExtra("extra_text").toString();
if (text.equals("1")) {
editText2.setText(phone);
}
else if (text == "2") {
editText3.setText(phone);
}
else (text == "3") {
editText4.setText(phone);
}

Android Fabric Twitter share listener

I use Fabric SDK to send tweets from my application.
I build a share dialog and send tweet from activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TwitterAuthConfig authConfig = new TwitterAuthConfig(CONSUMER_KEY, CONSUMER_SECRET);
Fabric.with(this, new TwitterCore(authConfig), new TweetComposer());
Bundle bundle = getIntent().getExtras().getBundle(SHARE_DATA);
String description = bundle.getString(SHARE_DESCRIPTION);
String title = bundle.getString(SHARE_TITLE);
String picture = bundle.getString(SHARE_PICTURE_LINK);
String link = bundle.getString(SHARE_LINK);
TweetComposer.Builder builder = null;
try {
InputStream in = new java.net.URL(picture).openStream();
Bitmap bitmap = BitmapFactory.decodeStream(in);
Uri yourUri = getImageUri(this,bitmap);
builder = new TweetComposer.Builder(this)
.text(title + "\n" + description)
.url(new URL(link))
.image(yourUri);
//??? IS THERE ANY LISTENER ???
builder.show();
} catch (IOException e1) {
e1.printStackTrace();
}
}
I want to know status of sharing, like an success or not, but i can't find any listener for this action. I missed something?
Instead of use builder.show(), you should use builder.createIntent() :
Intent intent = new TweetComposer.Builder(getActivity())
.text("TEXT")
.url("URL")
.createIntent();
startActivityForResult(intent, TWEET_COMPOSER_REQUEST_CODE);
To get the result feedback in onActivityResult() :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == TWEET_COMPOSER_REQUEST_CODE) {
if(resultCode == Activity.RESULT_OK) {
onTwitterSuccess();
} else if(resultCode == Activity.RESULT_CANCELED) {
onTwitterCancel();
}
}
}
use below method to twitt via rest service and pass media id as null.i m successfully posting tweets from my app
public void postToTwitter(ArrayList<String>mediaIds) {
String message;
if(Validator.isNotNull(preferences.getFbShareMessage())){
message=preferences.getFbShareMessage()+" "+com.aimdek.healthwel.network.Request.HOST_URL + "/user-history/" + userHistory.getUserId() + "/" + userHistory.getId();
}
else {
message = getString(R.string.google_status, HWUtil.getFullName(preferences.getUserInfo().getFirstName(), preferences.getUserInfo().getLastName()), userHistory.getSportName(), HWUtil.secondToTime(userHistory.getDuration()))+" "+com.aimdek.healthwel.network.Request.HOST_URL + "/user-history/" + userHistory.getUserId() + "/" + userHistory.getId();
}
String mediaId;
if (Validator.isNotNull(mediaIds) && mediaIds.size() > 0) {
mediaId="";
for (int i = 0; i < mediaIds.size(); i++) {
if (i == 0) {
mediaId = mediaIds.get(i);
} else {
mediaId += "," + mediaIds.get(i);
}
}
}
else {
mediaId=null;
}
StatusesService statusesService = twitterApiClient.getStatusesService();
statusesService.update(message, null, null, null, null, null, null, null, mediaId, new Callback<Tweet>() {
#Override
public void success(Result<Tweet> result) {
dismissProgressDialog();
if(Validator.isNotNull(preferences.getImagePath()) && !preferences.getImagePath().isEmpty()) {
preferences.getImagePath().clear();
}
com.aimdek.healthwel.network.Request.getRequest().sendRequest(com.aimdek.healthwel.network.Request.SHARE_USER_HISTORY, TwitterIntegration.this, TwitterIntegration.this, RequestParameterBuilder.buildMapForShareUserHistory(userHistory.getId(), TwitterIntegration.this));
}
#Override
public void failure(TwitterException exception) {
if(Validator.isNotNull(preferences.getImagePath()) && !preferences.getImagePath().isEmpty()) {
preferences.getImagePath().clear();
}
dismissProgressDialog();
finish();
HWUtil.showToast(TwitterIntegration.this,exception.getMessage());
}
});
}

android: onSaveInstanceState ()

I try to pass a string from one activity to another activity.
This is the coding in Activity A:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString("UserName", UserName);
Log.i(Tag, "UserName1: "+ UserName);
super.onSaveInstanceState(savedInstanceState);
}
In Activity B I use this code to get the string:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_item);
setUpViews();
if (savedInstanceState != null){
UserName = savedInstanceState.getString("UserName");
}
Log.i(Tag, "UserName2: "+ UserName);
}
But the logcat shown the first log "UserName1" when I clikc the open to Activity B,
and show the second log "UserName2" as "null".
May I know what wrong with my code?
What I want to do is Activity A pass the String in Activity B when I click the "button" and intent to Activity B. So I can get the String value in Activity B.
Any Idea? Cause I getting error when using intent.putStringExtra() and getintent.getStringExtra(), so I change to use onSaveInstanceState (), but still having problem.
EDIT:
This is my original code, I can get the String in Activity B, but unexpected I can't save my data in Sqlite. If remove the putString Extra then everything go smoothly.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent addItem = new Intent(ItemActivity.this, AddEditItem.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
addItem.putStringExtra("UserName", UserName);
Log.e(Tag, "UseName: "+ UserName);
startActivity(addItem);
return super.onOptionsItemSelected(item);
}
Code in Activity B:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_item);
setUpViews();
UserName = (String) getIntent().getStringExtra("UserName");
Log.e(Tag, "UserName3: "+ UserName);
}
Full code for Activity B:
public class AddEditItem extends Activity implements OnItemSelectedListener {
private static final String Tag = null;
private EditText inputItemName;
private EditText inputItemCondition;
private EditText inputEmail;
private Button btnGal, btnConfirm;
private Bitmap bmp;
private ImageView ivGalImg;
private Spinner spinner;
String[] category = {"Books", "Clothes & Shoes", "Computer", "Electronics", "Entertainment", "Food & Drinks",
"Furnitures", "Mobile Phone", "Other", "UKM"};
String selection;
String filePath, itemName, itemCondition;
String UserName, user;
private int id;
private byte[] blob=null;
byte[] byteImage2 = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_item);
setUpViews();
if (savedInstanceState != null){
UserName = savedInstanceState.getString("UserName");
}
Log.e(Tag, "UserName2: "+ UserName);
//UserName = (String) getIntent().getStringExtra("UserName");
//Log.e(Tag, "UserName3: "+ UserName);
}
private void setUpViews() {
inputItemName = (EditText)findViewById(R.id.etItemName);
inputItemCondition = (EditText)findViewById(R.id.etItemCondition);
inputEmail = (EditText)findViewById(R.id.etEmail);
ivGalImg = (ImageView) findViewById(R.id.ivImage);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(AddEditItem.this, android.R.layout.simple_spinner_dropdown_item, category);
spinner = (Spinner)findViewById(R.id.spnCategory);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
Bundle extras = getIntent().getExtras();
if (extras != null) {
id=extras.getInt("id");
user=extras.getString("user");
inputItemName.setText(extras.getString("name"));
inputItemCondition.setText(extras.getString("condition"));
inputEmail.setText(extras.getString("email"));
selection = extras.getString("category");
byteImage2 = extras.getByteArray("blob");
if (byteImage2 != null) {
if (byteImage2.length > 3) {
ivGalImg.setImageBitmap(BitmapFactory.decodeByteArray(byteImage2,0,byteImage2.length));
}
}
}
btnGal = (Button) findViewById(R.id.bGallary);
btnGal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 0);
}
});
btnConfirm = (Button) findViewById(R.id.bConfirm);
btnConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (inputItemName.getText().length() != 0 && inputItemCondition.getText().length() != 0
&& inputEmail.getText().length() != 0) {
AsyncTask<Object, Object, Object> saveItemTask = new AsyncTask<Object, Object, Object>() {
#Override
protected Object doInBackground(Object... params) {
saveItem();
return null;
}
#Override
protected void onPostExecute(Object result) {
Toast.makeText(getApplicationContext(),
"Item saved", Toast.LENGTH_LONG)
.show();
finish();
}
};
saveItemTask.execute((Object[]) null);
Toast.makeText(getApplicationContext(),
"Item saved reconfirm", Toast.LENGTH_LONG)
.show();
} else {
AlertDialog.Builder alert = new AlertDialog.Builder(
AddEditItem.this);
alert.setTitle("Error In Save Item");
alert.setMessage("You need to fill in all the item details");
alert.setPositiveButton("OK", null);
alert.show();
}
}
});
}
private void saveItem() {
if(bmp!=null){
ByteArrayOutputStream outStr = new ByteArrayOutputStream();
bmp.compress(CompressFormat.JPEG, 100, outStr);
blob = outStr.toByteArray();
}
else{blob=byteImage2;}
ItemSQLiteConnector sqlCon = new ItemSQLiteConnector(this);
if (getIntent().getExtras() == null) {
sqlCon.insertItem(UserName, inputItemName.getText().toString(),
inputItemCondition.getText().toString(),
inputEmail.getText().toString(),
selection, blob);
}
else {
sqlCon.updateItem(id, UserName, inputItemName.getText().toString(),
inputItemCondition.getText().toString(),
inputEmail.getText().toString(),
selection, blob);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode,Intent resultdata) {
super.onActivityResult(requestCode, resultCode, resultdata);
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
Uri selectedImage = resultdata.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
// Convert file path into bitmap image using below line.
bmp = BitmapFactory.decodeFile(filePath);
ivGalImg.setImageBitmap(bmp);
}
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// TODO Auto-generated method stub
TextView tv = (TextView)view;
selection = tv.getText().toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
onSaveInstanceState is not used in that purpose, its used to save your activity state on for example orientation change, or when you leave an activity and get back to it.
What you need is to use intents.
Other than starting activity, intents can also carry some information throughout app, like this:
This would be activity 1:
Intent = new Intent (getApplicationContext(), Activity2.class);
intent.putExtra("UserName", UserName);
startActivity(intent);
and to recover it in second activity use:
String username = getIntent().getExtras().getString("UserName");
May I know what wrong with my code?
onSaveInstanceState() has nothing to do with passing data between activities. Instead, you need to put your string in an extra on the Intent used with startActivity().
Cause I getting error when using intent.putExtra() and getintent.getExtra()
Since that is the correct approach (albeit using getStringExtra()), please go back to it and fix whatever error you are encountering.

Categories

Resources