how update a textview - android

simple program: 2 buttons (previous/next) and a textview to show text.
by intent I created an Index (inside a method)
private void index(){
Intent i = new Intent(this, Index.class);
startActivityForResult(i, 1);
}
Index.class (with 3 buttons):
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String result = "1";
Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(RESULT_OK,returnIntent);
finish();
}
});
Main.class
String value = "1";
final String prog1[] = new String[16];
final String prog2[] = new String[105];
final String prog3[] = new String[66];
int a;
int b;
int c=3;
int array1start = 0; int array1end = 15;
int array2start = 0; int array2end = 105;
int array3start = 0; int array3end = 65;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
if (value.equals("1")){
a = array1start;
b = array1end;
prog=prog1;
}
else if (value.equals("2")){
a = array2start;
b = array2end;
prog=prog2;
textView1.setText(""+prog[a]);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
String result=data.getStringExtra("result");
value=result;
Toast toast2=Toast.makeText(this,"value: "+value,Toast.LENGTH_LONG);
toast2.show();
}
if (resultCode == RESULT_CANCELED) {
//Write your code on no result return
}}
}//onAcrivityResult
at this point, choosen choice in index class should be change a result string to "value" string in main class
private void index(){
Intent i = new Intent(this, Index.class);
startActivityForResult(i, 1);
}
my textview take data from array1 or array2 by index class
so, I dont' understand how update textview (because index value is correct).
thanks for the help

Put you code into function onActivityResult
if (value.equals("1")){
a = array1start;
b = array1end;
prog=prog1;
}
else if (value.equals("2")){
a = array2start;
b = array2end;
prog=prog2;
textView1.setText(""+prog[a]);

Related

Startactivity for result with causes crash

I am trying to learn Android Studio and my first app is a blood alcohol calculator. The user starts that app and then a new activity is started so that they can enter their weight and press ok, this returns them back to the main activity and fills in the weight text.
I use startActivityForResult and then putExtra in the second activity. The first activity crashes if I use the getExtra method, if I delete the 2 receiving lines of code then there is no crash. When I use the debugger it says NullPointerException just before it says App has stopped working
Main activity code
public class MainActivity extends Activity {
static int displayunit = 0;
static double percentage = 5.0;
static int change = 1;
static double bah;
static double vol = 25;
static double timestamp = 0;
static double w = 0;
static String we = "a";
final int rcode = 3;
final String[] units = {"Small Shot(25ml)", "Large Shot(35ml)", "Small
Port/Sherry(50ml)", "Large Port/Sherry(70ml)", "Small Wine(125ml)",
"Large
Wine(175ml)", "Small Beer Bottle(284ml)", "Half Pint(236.6ml)", "Medium
Beer Bottle(330ml)", "Can of beer(440ml)", "Large Bottle(500ml)",
"Pint(568.26ml)", "Massive Beer Bottle(660ml)"};
final int[] unitsum = {25, 35, 50, 70, 125, 175, 284, 237, 330, 440, 500,
569, 660};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent();
intent.setClassName("com.example.alccalc","com.example.alccalc.enterweight");
if(w ==0){
startActivityForResult(intent, rcode);
}
}
#Override
protected void onActivityResult ( int requstCode, int resultCode,
Intent intent){
if (requstCode == rcode && resultCode == RESULT_OK) {
we = getIntent().getStringExtra("weighttext");
w = Double.parseDouble(we);
}
TextView kg = (TextView) findViewById(R.id.kg);
kg.setText(we)
Second Activity
public class enterweight extends Activity {
EditText entweight;
TextView tester;
String weightstring;
#Override
protected void onCreate(Bundle State) {
super.onCreate(State);
setContentView(R.layout.activity_enterweight);
entweight = (EditText) findViewById(R.id.entweight);
tester = (TextView)findViewById(R.id.tester);
Button okweight = (Button) findViewById(R.id.okweight);
okweight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
weightstring = entweight.getText().toString();
//tester.setText(weightstring);
Intent intent = new Intent();
intent.putExtra
("weighttext", weightstring);
setResult(RESULT_OK, intent);
if (intent.hasExtra("weighttext")) {
finish();
}
}
});
}
}
The error is here getIntent();
Since you are using the onActivityResult ( int requstCode, int resultCode,
Intent intent) method, you can find your extras in the variable intent. The method getIntent() returns the intent that is used to start the activity. In your case it is null.
Use:
we = intent.getStringExtra("weighttext");
instead of
we = getIntent().getStringExtra("weighttext");
Better:
Bundle extras = intent.getExtras();
if (extras != null) {
String result = extras.getString("weighttext");
.....
}
Try this in your receiving code
Intent intent= getIntent();
Bundle b = intent.getExtras();
if(b != null)
we = b.getString("weighttext");
You are calling getIntent() to get the result data. getIntent() is an activity method that returns an intent that is used to start the activity. You should use the intent variable that is passed on onActivityResult method.
if (requstCode == rcode && resultCode == RESULT_OK) {
we = intent.getStringExtra("weighttext");
w = Double.parseDouble(we);
}

Xamarin System Don't know about Android.Graphics.Bitmap

So i was trying to resize images with using android graphics bitmap. There is no error in code but when i build the project it throws out "System.NotSupportedException: Don't know about Android.Graphics.Bitmap" exception.
I tried ticking Common Language Runtime Exceptions and rebuilding the project both didnt work.
Here is my code
[Activity(MainLauncher = false, Theme = "#style/MyTheme")]
public class Duzenle_Activity : ActionBarActivity
{
public static ListView liw;
Intent intent = new Intent();
public Dialog dialog;
public static int toplam_hesap_tutucu;
public static Duzenle_Adapter adapt;
public static TextView toplam;
private BackgroundWorker bw = new BackgroundWorker();
public static int toplam_hesap = 0;
public List<Sepet> gecici_sepet;
List<Yemek_Liste> yemek_ = new List<Yemek_Liste>();
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.menu_duzenle);
var toolbar = FindViewById<Toolbar>(Resource.Id.toolbar);
SetSupportActionBar(toolbar);
SupportActionBar.Title = "Duzenle";
yemek_ = MainActivity.db.selectItem();
liw = FindViewById<ListView>(Resource.Id.listv_duzenle);
adapt = new Duzenle_Adapter(this, Resource.Layout.duzenle_model, yemek_,this);
liw.Adapter = adapt;
var toolbarBottom = FindViewById<Toolbar>(Resource.Id.toolbar_bottom_duzenle);
toolbarBottom.InflateMenu(Resource.Menu.ekle_action);
toolbarBottom.MenuItemClick += (sender, e) =>
{
if (e.Item.TitleFormatted.ToString() == "Ekle")
{
var transaction = FragmentManager.BeginTransaction();
var dialogFragment = new Dialog_Ekle(this);
dialogFragment.Show(transaction, "dialog_fragment");
}
};
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (resultCode == Result.Ok)
{
Duzenle_Adapter adapter = ((Duzenle_Adapter)liw.Adapter);
Bitmap mBitmap = null;
mBitmap = Android.Provider.MediaStore.Images.Media.GetBitmap(ContentResolver, data.Data);
Bitmap originalImage = BitmapFactory.DecodeByteArray(mBitmap.ToArray<Byte>(), 0, mBitmap.ByteCount);
Bitmap resizedImage = Bitmap.CreateScaledBitmap(originalImage, 25, 25, false);
adapter.al_getir().adresler = resizedImage;
adapter.NotifyDataSetChanged();
Console.WriteLine("ADRES1" + " " + data.Data);
}
}
public void tikla()
{
var imageIntent = new Intent();
imageIntent.SetType("image/*");
imageIntent.SetAction(Intent.ActionGetContent);
StartActivityForResult(
Intent.CreateChooser(imageIntent, "Select photo"), 0);
}
}
And i get the image from gallery as uri.
Edit : Why is it throwing this exception when there is no error in code. Its actually strange. It cant be about the android.graphics library right?
Edit 2 : I save these bitmaps to database and then display it in listview
Bitmap a = sepet[position].adres;
tut.img.SetImageBitmap(a);
Based on what I got earlier from you please try this:
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (resultCode == Result.Ok)
{
Duzenle_Adapter adapter = ((Duzenle_Adapter)listView1.Adapter);
//adapter.SelectedYemek.ImageUri = data.Data;
var mBitmap = Android.Provider.MediaStore.Images.Media.GetBitmap(ContentResolver, data.Data);
adapter.SelectedYemek.ImageBitmap = Bitmap.CreateScaledBitmap(mBitmap, 80, 80, false);
adapter.NotifyDataSetChanged();
}
}

why the captured image keep on changing?

I'm trying to pass captured image and valuefrom C to B, finally to listView A. When the list in Activity A is clicked, it will display the passed image on imageView and values on editText B . But the problem now is the image displayed on Activity B is not from row I have clicked on listview A.
Activity A
ArrayAdapter<String> adapter;
ArrayList<String> m_listItems = new ArrayList<String>();
int mClickedPosition;
adapter=new ArrayAdapter<String (getActivity(),R.layout.claims,R.id.textView1,m_listItems);
listV = (ListView) claims.findViewById(R.id.listView1);
listV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> listView, View view,int position, long id)
{
mClickedPosition = position;
String temp[] = m_listItems.get(position).split("\\s\\s+");
result = temp[temp.length - 1].trim();
result = result.replace("RM", "");
name = temp[1].trim();
Log.e("TAG", result + "");
if (name.equals("Project"))
{
Intent intent = new Intent(Claims1.this.getActivity(), Project1.class);
intent.putExtra("bitmap", true);
intent.putExtra("name", name);
intent.putExtra("result", result);
startActivityForResult(intent, 0);
Log.e("RESULT", "Result= " + result);
}
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 0: // for Project
result = data.getStringExtra("text"); //get from B
name = data.getStringExtra("a");
description = data.getStringExtra("c");
Log.d("FIRST", "result:" + result);
Text = " " + name + " " + "RM" + result + "";
if (mClickedPosition == -1)
{ // if is icon button clicked
m_listItems.add(Text);
}
else
{
m_listItems.set(mClickedPosition, Text);
}
adapter.notifyDataSetChanged();
listV.setAdapter(adapter);
break;
}
}
Activity B
if(getIntent().getExtras()!=null) { //if has value pass from A
final String Amount = getIntent().getExtras().getString("result");
final String description1 = getIntent().getExtras().getString("description");
txt1.setText(description1);
txt.setText(Amount);
}
b.setOnClickListener(new View.OnClickListener() { // return to A
public void onClick(View arg0) {
Intent returnIntent = new Intent();
a = "Project";
text = txt.getText().toString(); // amount
returnIntent.putExtra("text", text);
returnIntent.putExtra("a", a);
returnIntent.putExtra("c", c); // receive from Activity C
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
viewImage.setImageBitmap(Global.img); // image receive from C
}
public void onActivityResult(int requestCode,int resultCode, Intent data)
{ //receive from C
if(requestCode==PROJECT_REQUEST_CODE) {
if(data!=null&&data.hasExtra("text")) {
c = data.getStringExtra("text");
txt1.setText(c);
viewImage.setImageBitmap(Global.img); //display image
}
}
else if (requestCode==CAMERA_REQUEST_CODE)
{
}
}
Activity C
ImageView b;
ok.setOnClickListener(new View.OnClickListener()
{ // return image to B
public void onClick(View arg0)
{
Intent returnIntent=new Intent();
text=t.getText().toString();
b.setDrawingCacheEnabled(true);
b.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
b.layout(0, 0, b.getMeasuredWidth(), b.getMeasuredHeight());
b.buildDrawingCache(true);
returnIntent.putExtra("text", text);
if (b.getDrawingCache() != null) {
Bitmap bitmap = Bitmap.createBitmap(b.getDrawingCache());
if (bitmap == null) {
Log.e("TAG", "getDrawingCache() == null");
}
Global.img = bitmap;
}
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
}
Add image into database
When ok button in Activity A is clicked, I want save all the image todatabase.
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
byte[] data=getBitmapAsByteArray(getActivity(),Global.img);// this is a function
SB.insertStaffBenefit(data);
}
}
}
public static byte[] getBitmapAsByteArray(final Context context,Bitmap bitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, outputStream);
Toast.makeText(context, outputStream.size()/1024+"KB", Toast.LENGTH_LONG).show();
return outputStream.toByteArray();
}
1: ListView in A. Values were get fom C and B.
2: Activity B. Assume the list is clicked and intent to B. Noted that the value and image are from Activity C and B.
3: New value and images added and return to A
4: Two list in Activity A now
5: When first list clicked, image changed
You may add bitmap array list (in your Activity A):
ArrayList<Bitmap> m_listBitmapItems = new ArrayList<Bitmap>();
in onItemClick of your listV:
Global.img = m_listBitmapItems.get(position);
in onActivityResult():
if (mClickedPosition == -1)
{ // if is icon button clicked
m_listItems.add(Text);
m_listBitmapItems.add(Global.img);
}
else
{
m_listItems.set(mClickedPosition, Text);
m_listBitmapItems.set(mClickedPosition, Global.img);
}

how to store data permanently in listview

i use this (link or code) to store id and password of user
http://techblogon.com/android-login-registration-screen-with-sqlite-database-example/
problem is i want to store list view item permanently in my listview when user login against their account
private static int RESULT_LOAD_IMAGE = 1;
private String currentImageName = "ic_launcher";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_ad_layout);
Button saveButton = (Button) findViewById(R.id.buttonSaveAdd);
saveButton.setOnClickListener(this);
Button buttonaddimage = (Button) findViewById(R.id.buttonAddImage);
buttonaddimage.setOnClickListener(this);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want Create a new Add?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
Intent intent = new Intent(Create_adds_Activity.this, Button_mak.class);
startActivity(intent);
}
});
builder.show();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonAddImage:
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
break;
case R.id.buttonSaveAdd:
EditText editTextTitle = (EditText) findViewById(R.id.editTextTitle);
EditText editTextDes = (EditText) findViewById(R.id.editTextDescription);
EditText editTextOwner = (EditText) findViewById(R.id.editTextOwnerName);
EditText editTextOwnerEmail = (EditText) findViewById(R.id.editTextOwnerEmail);
EditText editTextPrice = (EditText) findViewById(R.id.editTextPrice);
//populating data object from the values received
//from view
String title = editTextTitle.getText().toString();
String description = editTextDes.getText().toString();
String ownerName = editTextOwner.getText().toString();
String ownerEmail = editTextOwnerEmail.getText().toString();
String pricce = editTextPrice.getText().toString();
Advertisement object = new Advertisement(title, description,
ownerName, ownerEmail, currentImageName, Integer.parseInt(pricce), 100);
Button_mak.ads.add(object);
this.finish();
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.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 picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView10 = (ImageView) findViewById(R.id.creatae);
imageView10.setImageBitmap(BitmapFactory.decodeFile(picturePath));
currentImageName = ">>>"+picturePath;
}
i use array adapter
final Context context = this;
public static ArrayList<Advertisement> ads = new ArrayList<Advertisement>();
I would deffenitely recommend using SQLite to save your data.
In the beginning it might seem a bit complex, but when ur used to it, its an ease.
Here's a handy little tutorial: http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/

I am trying to export a single contact from the address book to .vcf. Where am I going wrong?

package com.example.address_book;import android.app.Activity;import android.content.Intent;import android.database.Cursor;import android.net.Uri;import android.os.Bundle;import android.provider.ContactsContract.CommonDataKinds.Phone;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.ImageButton;import android.widget.Toast;
public class MainActivity extends Activity {
private static final int PICK_CONTACT_REQUEST = 1;
String[] num={" "," "};
String number1;
#Overrideprotected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{ImageButton add_me = (ImageButton) findViewById(R.id.imageButton1);
add_me.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
pickContactIntent.setType(Phone.CONTENT_TYPE);startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
}
});
}catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
int n=0;int n1=0;
if (requestCode == PICK_CONTACT_REQUEST){
if (resultCode == RESULT_OK){
Uri stuff = data.getData();Intent in = new Intent(android.content.Intent.ACTION_VIEW, stuff);
in.setType("text/x-vcard");
startActivity(in);
String[] projection = {Phone.NUMBER};Cursor cursor = getContentResolver().query(stuff, projection, null, null, null);cursor.moveToFirst();
int column = cursor.getColumnIndex(Phone.NUMBER);
number1 = cursor.getString(column);
n++;number1 = number1.replace("-" ,"");
for(int i=0;i<num.length;i++){num[i]=number1;
}
}
}
}
#Overridepublic boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.main, menu);return true;
}
}
Try with this dude it will open your contact jusr pass contactId in this
Intent intent = new Intent(Intent.ACTION_VIEW);
//pass your contact id
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, String.valueOf(contactId));
intent.setData(uri);
mcntxt.startActivity(intent);

Categories

Resources