Retrieve item from Spinner and put Some conditions - java

i have 2 arrays first for Hours and second for minutes, this is my arrays declare it in string.xml
` <string-array name="feedbacktypelist">
<item>#string/hr0</item>
<item>#string/hr1</item>
<item>#string/hr2</item>
</string-array>
<string-array name="array2">
<item>#string/min5</item>
<item>#string/min10</item>
<item>#string/min15</item>
<item>#string/min20</item>
<item>#string/min25</item>
<item>#string/min30</item>
<item>#string/min35</item>
<item>#string/min40</item>
<item>#string/min45</item>
<item>#string/min50</item>
<item>#string/min55</item>
<item>#string/min59</item>
</string-array>`
and this is my code in java
package lmp.app.pkg;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class CreateNewForm extends Activity implements OnItemSelectedListener {
Button Browse;
ImageView CasePic;
Spinner CaseDurationH, CaseDurationM;
TextView tesst;
RadioGroup GenderSelection;
EditText CaseName, CaseClothes, CaseMoreInfo, CaseAge;
Button Next;
//For Browsering Picture
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.create_new_form);
//To Call initializer Function
initializer();
//j list
// 1-For Uploading Picture
Browse.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// in onCreate or any event where your want the user to
// select a file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), SELECT_PICTURE);
}
});
// 1-Name
final MyCase case1 = new MyCase();
case1.setName(CaseName.getText().toString());
// 2-Gender For Group Radio
GenderSelection.clearCheck();
GenderSelection.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.radio0:
case1.setGender("Male");
break;
case R.id.radio1:
case1.setGender("Female");
break;
default:
break;
}
}
});
//3-Age
String age = CaseAge.getText().toString();
/*int tstnum =case1.getAge();
tesst.setText(tstnum); */
//4-Duration Time
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.feedbacktypelist, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
CaseDurationH.setAdapter(adapter);
//5-Case Clothes
case1.setClothes(CaseClothes.getText().toString());
//6-Case More Information
case1.setMoreInfo(CaseMoreInfo.getText().toString());
//Move to 2nd form page
Next= (Button)findViewById(R.id.Next2);
Next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.Next2:
try
{
Intent k = new Intent(CreateNewForm.this, CreateNewForm_2.class);
startActivity(k);
}catch(Exception e){
}
break;
}
}
});
//Spinner
CaseDurationH.setOnItemSelectedListener(new OnItemSelectedListener() {
int i =CaseDurationH.getSelectedItemPosition();
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
int i = CaseDurationH.getSelectedItemPosition();
if(i==2){
CaseDurationM.setEnabled(false);
}
String str = parent.getSelectedItem().toString();
if(str.equals("hr0"))
{
}
if(str.equals("hr1"))
{
}
if(str.equals("hr2"))
{
CaseDurationM.setEnabled(false);
}
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
} });
}
// To initialize the variables
private void initializer() {
// TODO Auto-generated method stub
//This information will be filled by a user
//CasePic = (ImageView) findViewById(R.id.imageView1);
CaseName= (EditText) findViewById(R.id.caseNm);
GenderSelection= (RadioGroup) findViewById(R.id.radioGroup1);
CaseAge= (EditText) findViewById(R.id.caseaage);
tesst= (TextView) findViewById(R.id.textView8);
CaseDurationH= (Spinner) findViewById(R.id.Shr);
CaseDurationM= (Spinner) findViewById(R.id.Smin);
CaseClothes= (EditText) findViewById(R.id.caseClothes);
CaseMoreInfo= (EditText) findViewById(R.id.caseMrInfo);
CasePic = (ImageView) findViewById(R.id.casepic);
Browse = (Button) findViewById(R.id.browseCasePic);
}
//For Uploading Picture
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
}
}
}
//For Uploading Picture
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
i want:
1- retrieve the item in spinner that the user choose it, not the positon
2-if the user choose from spinner1 the item "hr02" then the spinner2 will disable
Thank you for help me, StackOverFlow members your my hero now! :")

use this
String str = parent.getSelectedItem().toString();
if(str.equals("hr2")
{
spinner2.setEnabled(false);
}

Try this:
String str = parent.getSelectedItem().toString();
if (str.equals("hr0")){
//retrieve the item as string
}
if (str.equals("hr1")){
//retrieve the item as string
}
if (str.equals("hr2")){
//retrieve the item as string
//make the 2nd spinner disable
}

Related

stuck on loading image while trying to set image as wallpaper

i am creating images gallery wallpaper app in which i am trying to set image as wallpaper.
when i try to set a image as wallpaper i gets stuck at image loading message.
this is the screenshot: it gets stuck here:
tThis is the set wallpaper code:
set_wallpaper.java
package com.td.gridview;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.WallpaperManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class Set_Wallpaper extends Activity {
private Uri mImageCaptureUri;
private ImageView mImageView;
private AlertDialog dialog;
private static final int PICK_FROM_CAMERA = 1;
private static final int CROP_FROM_CAMERA = 2;
private static final int PICK_FROM_FILE = 3;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.set_wallpaper);
// get intent data
Intent i = getIntent();
// Selected image id
int position = i.getExtras().getInt("id");
ImageView ing = (ImageView) findViewById(R.id.image_page);
ing.setImageResource(MainActivity.ICONS[position]);
doCrop();
}
private void doCrop() {
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
/**
* Open image crop app by starting an intent
* ‘com.android.camera.action.CROP‘.
*/
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
/**
* Check if there is image cropper app installed.
*/
List<ResolveInfo> list = getPackageManager().queryIntentActivities(
intent, 0);
int size = list.size();
/**
* If there is no image cropper app, display warning message
*/
if (size == 0) {
Toast.makeText(this, "Can not find image crop app",
Toast.LENGTH_SHORT).show();
return;
} else {
/**
* Specify the image path, crop dimension and scale
*/
intent.setData(mImageCaptureUri);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
/**
* There is posibility when more than one image cropper app exist,
* so we have to check for it first. If there is only one app, open
* then app.
*/
if (size == 1) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent(new ComponentName(res.activityInfo.packageName,
res.activityInfo.name));
startActivityForResult(i, CROP_FROM_CAMERA);
} else {
/**
* If there are several app exist, create a custom chooser to
* let user selects the app.
*/
for (ResolveInfo res : list) {
final CropOption co = new CropOption();
co.title = getPackageManager().getApplicationLabel(
res.activityInfo.applicationInfo);
co.icon = getPackageManager().getApplicationIcon(
res.activityInfo.applicationInfo);
co.appIntent = new Intent(intent);
co.appIntent
.setComponent(new ComponentName(
res.activityInfo.packageName,
res.activityInfo.name));
cropOptions.add(co);
}
CropOptionAdapter adapter = new CropOptionAdapter(
getApplicationContext(), cropOptions);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose Crop App");
builder.setAdapter(adapter,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
startActivityForResult(
cropOptions.get(item).appIntent,
CROP_FROM_CAMERA);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
if (mImageCaptureUri != null) {
getContentResolver().delete(mImageCaptureUri, null,
null);
mImageCaptureUri = null;
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
}
public class CropOption {
public CharSequence title;
public Drawable icon;
public Intent appIntent;
}
public class CropOptionAdapter extends ArrayAdapter<CropOption> {
private ArrayList<CropOption> mOptions;
private LayoutInflater mInflater;
public CropOptionAdapter(Context context, ArrayList<CropOption> options) {
super(context, R.layout.set_wallpaper, options);
mOptions = options;
mInflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup group) {
if (convertView == null)
convertView = mInflater.inflate(R.layout.set_wallpaper, null);
CropOption item = mOptions.get(position);
if (item != null) {
((ImageView) convertView.findViewById(R.id.image_page))
.setImageDrawable(item.icon);
((TextView) convertView.findViewById(R.id.tv_name))
.setText(item.title);
return convertView;
}
return null;
}
}
}
The following the code where i am swiping images and sending current showing image to set_wallpaper class on button click
SwipeActivity.java
package com.td.gridview;
import java.io.IOException;
import android.app.Activity;
import android.app.WallpaperManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
public class SwipeActivity extends Activity {
protected int curruntPosition;
protected int hh;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.swipe_view);
// get intent data
Intent i = getIntent();
// Selected image id
final int position = i.getExtras().getInt("id");
final ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(position);
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
// Here you can set the wallpaper
curruntPosition = arg0;
if (curruntPosition == arg0) {
hh = 1;
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
//
Button bx = (Button) findViewById(R.id.xoom);
bx.setOnClickListener(new View.OnClickListener() {
public void onClick(View vx) {
// // TODO Auto-generated method stub
if (hh == 1) {
// Sending image id to FullScreenActivity
Intent i2 = new Intent(getApplicationContext(),
Full_Zoom.class);
// passing array index
i2.putExtra("id", curruntPosition);
startActivity(i2);
} else {
// get intent data
Intent i3 = getIntent();
// Selected image id
int position = i3.getExtras().getInt("id");
// Sending image id to FullScreenActivity
Intent i2 = new Intent(getApplicationContext(),
Full_Zoom.class);
// passing array index
i2.putExtra("id", position);
startActivity(i2);
}
}
});
//
// set wallpaper on button click
Button b1 = (Button) findViewById(R.id.wll);
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v2) {
// // TODO Auto-generated method stub
if (hh == 1) {
// Sending image id to FullScreenActivity
Intent i2 = new Intent(getApplicationContext(),
Set_Wallpaper.class);
// passing array index
i2.putExtra("id", curruntPosition);
startActivity(i2);
} else {
// get intent data
Intent i3 = getIntent();
// Selected image id
int position = i3.getExtras().getInt("id");
// Sending image id to FullScreenActivity
Intent i2 = new Intent(getApplicationContext(),
Set_Wallpaper.class);
// passing array index
i2.putExtra("id", position);
startActivity(i2);
}
}
});
}
public class ImagePagerAdapter extends PagerAdapter {
int[] icons = MainActivity.ICONS;
#Override
public int getCount() {
return icons.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = SwipeActivity.this;
ImageView imageView = new ImageView(context);
// int padding = context.getResources().getDimensionPixelSize(
// R.dimen.padding_large);
// imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setImageResource(icons[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
}

Set OnclickListener For ListView Such that line selected in list is used as edit text in another class

I have two classes for my translation app. One(Voice.java) in which we speak and RecognizerIntent gets our speech and displays it in form of a list. This is voice.java
package com.example.testing;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class Voice extends Activity implements OnClickListener{
ListView lv;
static final int check=1111;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.voice);
lv=(ListView)findViewById(R.id.lvVoiceReturn);
Button b=(Button)findViewById(R.id.bVoice);
b.setOnClickListener(this);
lv.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch(arg0.getId()){
case R.id.bVoice:
Intent i=new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
i.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak Up");
startActivityForResult(i, check);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == check && resultCode==RESULT_OK){
ArrayList<String> results=data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,results));
}
super.onActivityResult(requestCode, resultCode, data);
}
}
And another class TranslateActivity which has one button and two edit text. Button works as translator of text from 1st edit text to translated text in second edit Text and speaks the translated text also . Code is as follows:
package com.example.testing;
import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import com.memetix.mst.language.Language;
import com.memetix.mst.translate.Translate;
public class TranslateActivity extends Activity implements OnClickListener {
EditText etInput
;
EditText etOutput;
TextToSpeech tts;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_translate);
Translate.setClientId("d6159b31-37ba-4668-a31f-de0de6c47a38");
Translate.setClientSecret("UMjSB3cHaSkLE+2xw4+a4dLIFahLdQQqh1YOhXdqfh4");
Button Trans = (Button)findViewById(R.id.translate);
etInput = (EditText)findViewById(R.id.input);
etOutput = (EditText)findViewById(R.id.output);
Trans.setOnClickListener(this);
tts =new TextToSpeech(TranslateActivity.this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
if(status !=TextToSpeech.ERROR){
tts.setLanguage(Locale.US);
}
}
});
}
#Override
public void onClick(View v) {
//get the text entered
String In =etInput.getText().toString();
String s[]=In.split(" ");
//String out[]= new String[3];
String str=new String();
String outString=new String();
//String Out;
try {
for(int i=0;i<s.length;i++){
if(s[i].equals("who")){
str="whoa";
//etOutput.setText("whoa");
//str=etOutput.getText().toString();
//tts.speak(str,TextToSpeech.QUEUE_FLUSH, null);
}else if(s[i].equals("are")){
// etOutput.setText("arey");
str="arey";
//str=etOutput.getText().toString();
//tts.speak(str,TextToSpeech.QUEUE_FLUSH, null);
}else if(s[i].equals("you")){
str="ram";
//etOutput.setText("your");
//str=etOutput.getText().toString();
//tts.speak(str,TextToSpeech.QUEUE_FLUSH, null);
}
outString+=str ;
outString+=" ";
}
tts.speak(outString,TextToSpeech.QUEUE_FLUSH, null);
// String Out = Translate.execute(In, Language.AUTO_DETECT, Language.FRENCH);
// etInput.setText(Out);
// etOutput.setText(Out);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Now I want an on click listener for list view such that whatever line I click on list View, it gets used as edit Text of 2nd class(TranslateActivity.java) and gets translated without clicking the button on 2nd class. That is functionality of button in 2nd class is done by just clicking on list view in 1st class.Anyone who knows how to do this?

how to use content provider to access shared preferences

i have a registration app in the making where the user registers the data and on the other end the data can be shown and viewed and manipulated , i am using shared preferences method as shown below to write and access data (you can see them in DataEntry.java & DataManipulation.java shown below) but i want to use content provider method to manipulate data like quering or inserting or deleting....is there a way to do this and if yes can you please tell me how?
thank you
here are the codes below
the User end DataEntry.java:
package com.hossa.datamanipulation;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class DataEntry extends Activity {
/*
* here is the part the user will submit several data for several people
*/
Button Submit, BroadcastButton;
TextView User, Email, Mobile;
EditText UserEdit, EmailEdit, MobileEdit;
String UserValue, EmailValue, MobileValue;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dataentry);
Submit = (Button) findViewById(R.id.DataSubmit);
BroadcastButton = (Button) findViewById(R.id.Broadcast);
User = (TextView) findViewById(R.id.TVuser);
Email = (TextView) findViewById(R.id.TVemail);
Mobile = (TextView) findViewById(R.id.TVmobile);
UserEdit = (EditText) findViewById(R.id.Edituser);
EmailEdit = (EditText) findViewById(R.id.Editemail);
MobileEdit = (EditText) findViewById(R.id.Editmobile);
Submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// saving the data of the user//
SharedPreferences sp = getSharedPreferences("userdata",
MODE_PRIVATE);// name of the file and it's mode//
SharedPreferences.Editor edit = sp.edit();// to be able to edit
// the file//
edit.putString("Username", UserEdit.getText().toString());// get
// the
// input
// username//
edit.putString("Email", EmailEdit.getText().toString());// get
// the
// input
// Email//
edit.putString("Mobile", MobileEdit.getText().toString());// get
// the
// input
// Mobile//
edit.commit();
Toast.makeText(getApplicationContext(),
"Data is Saved Successfully", Toast.LENGTH_SHORT)
.show();
}
});
BroadcastButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent e = new Intent();
e.setAction("com.hossa.data" + "manipulation.custombroadcast");
sendBroadcast(e);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
and the other end DataManipulaton.java:
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class DataManipulation extends Activity {
Button ImportButton, ViewButton, RetrieveButton;
EditText UserShow;
TextView EmailDisplay, UserDisplay, MobileDisplay, EmailTV, UserTV,
MobileTV;
public static final String defaultvalue = "N/A";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.datamanipulation);
ContentResolver ct = getContentResolver();
String Path = "data/data/com.hossa.datamanipulation/files/userdata";
Uri uri = Uri.parse("content://" + Path);
ImportButton = (Button) findViewById(R.id.ImportButton);
ViewButton = (Button) findViewById(R.id.ViewButton);
RetrieveButton = (Button) findViewById(R.id.RetrieveButton);
EmailDisplay = (TextView) findViewById(R.id.EmailDisplay);
MobileDisplay = (TextView) findViewById(R.id.MobileDisplay);
UserDisplay = (TextView) findViewById(R.id.UsernameDisplay);
EmailTV = (TextView) findViewById(R.id.EmailTV2);
UserTV = (TextView) findViewById(R.id.UserTV2);
MobileTV = (TextView) findViewById(R.id.MobileTV2);
final String U1[] = new String[10];
final String E1[] = new String[10];
final String M1[] = new String[10];
final String[][] alldata = new String[][] { U1, M1, E1 };
RetrieveButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int i = 0;
SharedPreferences spdata = getSharedPreferences("userdata",
Context.MODE_PRIVATE);
while (spdata.getString("Username", defaultvalue) != null) {
String tempuser = spdata
.getString("Username", defaultvalue);
U1[i] = tempuser;
i++;
}
i = 0;
while (spdata.getString("Email", defaultvalue) != null) {
String tempemail = spdata.getString("Email", defaultvalue);
E1[i] = tempemail;
i++;
}
i = 0;
while (spdata.getString("Mobile", defaultvalue) != null) {
String tempmobile = spdata
.getString("Mobile", defaultvalue);
M1[i] = tempmobile;
i++;
}
i = 0;
}
});
ImportButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
getApplicationContext();
// TODO Auto-generated method stub
SharedPreferences sp = getSharedPreferences("userdata",
Context.MODE_PRIVATE);
String Username = sp.getString("Username", defaultvalue);
String Email = sp.getString("Email", defaultvalue);
String Mobile = sp.getString("Mobile", defaultvalue);
// what if there is no data from the user??//
if (Username.equals(defaultvalue) || Email.equals(defaultvalue)
|| Mobile.equals(defaultvalue)) {
Toast.makeText(getApplicationContext(),
"no data has been entered", Toast.LENGTH_SHORT)
.show();
} else {
UserTV.setText(Username);
EmailTV.setText(Email);
MobileTV.setText(Mobile);
}
}
});
//THE BELOW IS THE SECTION I NEED HELP WITH...THE ABOVE IS SIMPLY SOME TRIALS AND TESTS//
Cursor c = ct.query(uri, U1, null, null, null);
// c=ct.delete(uri, where, selectionArgs);
// c=ct.update(uri, values, where, selectionArgs);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
PLEASE NOTE THAT BOTH CLASSES ARE IN THE SAME PACKAGE SO IT IS THE SAME APP NOT 2 DIFFERENT APPS

Shared Preferences doesn't get updated

I'm trying to make a world creator thing like in games and I am using shared preferences to store the arrays and such. But there is a problem. I am trying to update it from another class so I use static variables to do so. But when I go back to the original class with the list view, I find out that nothing has been updated. Any ideas? Here is the code. Oh and no errors came in the logcat.
ListView class.
package you.don't.need-to-know;
import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class WorldMenu extends ListActivity{
public static SharedPreferences prefs = null;
static String splitter;
String[] worldList;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
splitter = "Create World," + prefs.getString("worldString", "");
worldList = splitter.split(",");
setListAdapter(new ArrayAdapter<String>(WorldMenu.this,
android.R.layout.simple_list_item_1, worldList));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
if(position == 0){
Intent openWorldNamer = new
Intent("you.don't.need-to-know");
startActivity(openWorldNamer);
}
}
}
The Updater:
package you.don't.need-to-know;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class WorldCreator extends Activity{
EditText worldNameEditor;
Button saver;
static String updater;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_worldcreator);
worldNameEditor = (EditText) findViewById(R.id.editText1);
saver = (Button) findViewById(R.id.button1);
updater = worldNameEditor.getText().toString() + ",";
saver.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Editor editor = WorldMenu.prefs.edit();
editor.putString("worldString", updater);
editor.commit();
Intent openListWorld = new
Intent("you.don't.need.to-know");
startActivity(openListWorld);
}
});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}
Edit: New Code updated with closer to fixing. Updater and List Activity
Updater:
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class WorldCreator extends Activity{
EditText worldNameEditor;
Button saver;
SharedPreferences prefs;
OnSharedPreferenceChangeListener listener;
String updater;
Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_worldcreator);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
worldNameEditor = (EditText) findViewById(R.id.hello);
saver = (Button) findViewById(R.id.button1);
updater = worldNameEditor.getText().toString() + ",";
saver.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
listener = new SharedPreferences.OnSharedPreferenceChangeListener()
{
public void onSharedPreferenceChanged(SharedPreferences
prefs, String key) {
editor = prefs.edit();
editor.putString("worldString", updater);
editor.commit();
}
};
prefs.registerOnSharedPreferenceChangeListener(listener);
Intent openListWorld = new
Intent("");
startActivity(openListWorld);
}});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
}
List Activity:
import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class WorldMenu extends ListActivity{
SharedPreferences prefs = null;
String splitter;
String[] worldList;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
prefs = PreferenceManager.getDefaultSharedPreferences(this);
splitter = "Create World," + prefs.getString("worldString", "hello");
worldList = splitter.split(",");
setListAdapter(new ArrayAdapter<String>(WorldMenu.this,
android.R.layout.simple_list_item_1, worldList));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
if(position == 0){
Intent openWorldNamer = new
Intent("");
startActivity(openWorldNamer);
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
It doesn't look like you are monitoring for changes in the shared preferences. see:
http://developer.android.com/reference/android/content/SharedPreferences.OnSharedPreferenceChangeListener.html
final SharedPreferences.OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
// update your listview.
}
};
prefs.registerOnSharedPreferenceChangeListener(listener);
So when you get that callback, it will tell you what key changed. Then you could update the adapter for your listview to have the new contents and call onDataSetChanged() in the adapter.
Alternatively, you could move your adapter setting code into the onResume() function. This would make it so when your activity resumes, you check the status of the shared preferences and set the adapter. Be warned though, if the user has scrolled down the list some distance and you call setAdapter() again in the resume, they will lose their scroll position.
EDIT:
Try:
Updater (this shouldn't need to start a new activity, this can just finish()):
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class WorldCreator extends Activity{
EditText worldNameEditor;
Button saver;
SharedPreferences prefs;
OnSharedPreferenceChangeListener listener;
String updater;
Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_worldcreator);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
worldNameEditor = (EditText) findViewById(R.id.hello);
saver = (Button) findViewById(R.id.button1);
updater = worldNameEditor.getText().toString() + ",";
saver.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editor = prefs.edit();
editor.putString("worldString", updater);
editor.commit();
finish();
}});
}
ListView:
import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class WorldMenu extends ListActivity{
SharedPreferences prefs = null;
String splitter;
String[] worldList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
// update your listview.
}
};
prefs.registerOnSharedPreferenceChangeListener(listener);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
splitter = "Create World," + prefs.getString("worldString", "hello");
worldList = splitter.split(",");
setListAdapter(new ArrayAdapter<String>(WorldMenu.this,
android.R.layout.simple_list_item_1, worldList));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
if(position == 0){
Intent openWorldNamer = new
Intent("");
startActivity(openWorldNamer);
}
}
}
Prefrences are defined at the activity level. I'll have my bounty please.
Call getActivity() to get the callers activity then use that to get the prefrences.
If you want structure send results back via interface. Implement the interface and use the interface to find the activity. Eclipse creates stubs for you.
Here is the complete class that just changes a prefrence save's it and immediately sends the result back to the calling class. It uses getActivity() so the two classes share the same prefrences. It calls back through an interface.
It's from my app com.gosylvester.bestrides
package com.gosylvester.bestrides;
import com.google.android.gms.maps.GoogleMap;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
//...
public class MapSettings extends DialogFragment implements
OnCheckedChangeListener {
public static final String MAP_TYPE = "com.gosylvester.bestrides.settings.maptype";
private int _mapType = -1;
BestRidesSettingsDialogListener activity;
SharedPreferences sharedpref;
public interface BestRidesSettingsDialogListener {
void onMapSettingsChange(int mapType);
}
public MapSettings() {
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// the activity may be null if this is called without implementing the
// BestRidesSettingsDialogListener (The settings object saves the
// setting so the
// call back may not be needed.
activity = (BestRidesSettingsDialogListener) getActivity();
getDialog().setTitle(R.string.app_name);
View view = inflater.inflate(R.layout.activity_map_settings, container);
RadioGroup rg = (RadioGroup) view.findViewById(R.id.radioGroup1);
// initialize to the shared preferences value
rg.clearCheck();
sharedpref = getActivity().getPreferences(Context.MODE_PRIVATE);
int x = sharedpref.getInt(MAP_TYPE, GoogleMap.MAP_TYPE_NORMAL);
RadioButton rb = null;
switch (x) {
case GoogleMap.MAP_TYPE_HYBRID:
rb = (RadioButton) view.findViewById(R.id.RDOHybrid);
rb.setChecked(true);
break;
case GoogleMap.MAP_TYPE_NORMAL:
rb = (RadioButton) view.findViewById(R.id.RDORoad);
rb.setChecked(true);
break;
case GoogleMap.MAP_TYPE_SATELLITE:
rb = (RadioButton) view.findViewById(R.id.RDOSatelite);
rb.setChecked(true);
break;
case GoogleMap.MAP_TYPE_TERRAIN:
rb = (RadioButton) view.findViewById(R.id.RDOTerrain);
rb.setChecked(true);
break;
}
// set the listener after setting up
rg.setOnCheckedChangeListener(this);
return view;
}
public int getMapType() {
return _mapType;
}
public void setMapType(int mapType) {
this._mapType = mapType;
}
#Override
public void onCheckedChanged(RadioGroup rg, int checkId) {
// TODO Auto-generated method stub
int mapType = 0;
switch (checkId) {
case R.id.RDORoad:
mapType = GoogleMap.MAP_TYPE_NORMAL;
break;
case R.id.RDOHybrid:
mapType = GoogleMap.MAP_TYPE_HYBRID;
break;
case R.id.RDOSatelite:
mapType = GoogleMap.MAP_TYPE_SATELLITE;
break;
case R.id.RDOTerrain:
mapType = GoogleMap.MAP_TYPE_TERRAIN;
break;
}
// run the activity onchange
// if the activity is null there is no listener to take action on the
// settings
if (activity != null) {
activity.onMapSettingsChange(mapType);
}
// save the settings
if (sharedpref == null) {
sharedpref = getActivity().getPreferences(Context.MODE_PRIVATE);
}
sharedpref.edit().putInt(MAP_TYPE, mapType).commit();
}
}
/* here's a snipet of the other class */
public class KmlReader extends FragmentActivity implements
BestRidesSettingsDialogListener {
...
mMap.setMapType(sharedPref.getInt(
com.gosylvester.bestrides.MapSettings.MAP_TYPE,
GoogleMap.MAP_TYPE_NORMAL));
...
#Override
public void onMapSettingsChange(int mapType) {
// TODO Auto-generated method stub
if (mMap != null) {
mMap.setMapType(mapType);
}
}
Good Luck
Shared prefernces are meant to be used in multiple classes if all classes are in same process. You do not have to use static explicitely. Just use the same sharedprefernce in both classes.
when you go back to the original class it doesn't guarantee onCreate mothod of the original class can perform ,like other answers say ,you can put the code into onResume mothod ,or after startActivity(intent) add method finish() to finish current activity

Webview is blank or loading same page for different urls

A search api is returning me some meta data i.e a url "eventURL" and trackbackurl i.e "trackBack". I am placing the data in the listview, each row containing some data and a unique url and trackback url.When user taps on the row in the listview, a alert dialog is displayed presenting user 2 options. Clicking on option 1 should launch trackback url in a webview while clicking on second opion should launch eventURL in a webview.I have created a WebViewActivity for it,Problem is that my webview is always blank.
Main Activity
package my.stayactive.plan;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import my.stayactive.plan.ActiveHelper.ApiException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class StayActiveActivity extends Activity implements OnItemClickListener {
//private EditText m_search_text;
protected EditText m_zip;
private ListView m_search_results;
private Button m_search_btn;
private JSONArray m_results;
private LayoutInflater m_inflater;
private InputMethodManager m_ctrl;
private Spinner m_radius;
private Spinner m_activity_selector;
public static int radius = 0;
public static String activities;
public String url;
public String trackBack;
public static String assetId;
static final private int EXIT_ID = Menu.FIRST;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// m_search_text = (EditText) findViewById(R.id.search_text);
m_zip = (EditText) findViewById(R.id.zip);
m_search_btn = (Button) findViewById(R.id.search_button);
// m_searchm_results = (ListView) findViewById(R.id.lview);
m_search_btn .setOnClickListener(go_handler);
m_ctrl = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
m_inflater = LayoutInflater.from(this);
addListenerOnSpinnerItemSelection();
addListenerOnSpinner1ItemSelection();
m_search_results = (ListView)findViewById(R.id.lview);
m_search_results.setOnItemClickListener(this);
}
public void addListenerOnSpinnerItemSelection() {
m_radius = (Spinner) findViewById(R.id.spinner);
m_radius.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
public void addListenerOnSpinner1ItemSelection(){
m_activity_selector = (Spinner) findViewById(R.id.spinner1);
m_activity_selector.setOnItemSelectedListener(new ActivitySelectedListener());
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
menu.add(0, EXIT_ID, 0, R.string.exit);
return true;
}
#Override
public boolean onOptionsItemSelected (MenuItem item){
switch (item.getItemId()){
case EXIT_ID:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
OnClickListener go_handler = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//m_ctrl.hideSoftInputFromWindow(m_search_text.getWindowToken(), 0);
m_ctrl.hideSoftInputFromWindow(m_zip.getWindowToken(), 0);
//String searchText = Uri.encode(m_search_text.getText().toString());
String zip = Uri.encode(m_zip.getText().toString());
new SearchTask().execute("?k=Fall+Classic" + "&m=meta:channel=" + activities + "&l="+ zip + "&r=" + radius);
// Show a toast showing the search text
Toast.makeText(getApplicationContext(),
getString(R.string.search_msg) + " " +
activities, Toast.LENGTH_LONG).show();
}
};
private class SearchTask extends AsyncTask<String, Integer, String>
{
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(StayActiveActivity.this,"","Please Wait...");
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
String result = ActiveHelper.download(params [0]);
return result;
} catch (ApiException e) {
e.printStackTrace();
Log.e("alatta", "Problem making search request");
}
return "";
}
#Override
protected void onPostExecute(String result) {
dialog.hide();
try {
JSONObject obj = new JSONObject(result);
m_results = obj.getJSONArray("_results");
if (m_results == null || m_results.length() == 0)
{
Toast.makeText(getApplicationContext(),
"No Results found for " + activities,
Toast.LENGTH_LONG).show();
}
else
m_search_results.setAdapter(new JSONAdapter(getApplicationContext()));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private class JSONAdapter extends BaseAdapter
{
public JSONAdapter(Context c){
}
public int getCount()
{
return m_results.length();
}
public Object getItem(int arg0){
return null;
}
public long getItemId(int pos){
return pos;
}
public View getView(int pos, View convertView, ViewGroup parent) {
View tv;
TextView t;
if (convertView == null)
tv = m_inflater.inflate (R.layout.item, parent, false);
else
tv = convertView;
try {
/* For each entry in the ListView, we need to populate
* its text and timestamp */
t = (TextView) tv.findViewById(R.id.text);
JSONObject obj = m_results.getJSONObject(pos);
t.setText (obj.getString("title").replaceAll("</?(?i:<|>|...|&quot|&amp|;|)(.|\n)*?>", ""));
//("\\<.*?\\>", ""))
t = (TextView) tv.findViewById(R.id.created_at);
JSONObject meta = obj.getJSONObject("meta");
// url = meta.getString("eventURL");
trackBack = obj.getString("url");
assetId = meta.getString("assetTypeId");
//String eventDate = meta.getString("startDate");
Calendar currentDate = Calendar.getInstance();
long dateNow = currentDate.getTimeInMillis();
String eventDate = meta.getString("startDate");
String endDate = meta.getString("endDate");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
Date date2 = null;
try {
date = formatter.parse(eventDate);
date2 = formatter.parse(endDate);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long modifiedDate= date.getTime();
long modifiedEndDate = date2.getTime();
if ( Long.valueOf(dateNow).compareTo(Long.valueOf(modifiedDate)) > 0 || Long.valueOf(dateNow).compareTo(Long.valueOf(modifiedEndDate)) > 0)
{
t.setText ("Was:" + "\t"+eventDate+"\n"+"Location:" +"\t" +meta.getString("location")+"\n" + meta.getString("eventURL") +"\n"+ obj.getString("url"));
}
else {
t.setText ("When:" + "\t"+eventDate+"\n"+"Location:" +"\t" +meta.getString("location")+"\n"+ meta.getString("eventURL") +"\n"+ obj.getString("url"));
}
} catch (JSONException e) {
Log.e("alatta", e.getMessage());
}
return tv;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/*try {
JSONObject obj = m_results.getJSONObject(position);
JSONObject meta = obj.getJSONObject("meta");
url = meta.getString("eventURL");
//Intent intent = new Intent (StayActiveActivity.this, WebViewActivity.class);
//StayActiveActivity.this.startActivity(intent);
} catch (JSONException e) {
Log.e("alatta",e.getMessage());
}*/
// TODO Auto-generated method stub
final CharSequence[] items = {"Register", "Additional Information"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Please Select an Option");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
if (which == 0){
Intent intent1 = new Intent (StayActiveActivity.this, ReviewActivity.class);
StayActiveActivity.this.startActivity(intent1);
}
else if ( which == 1){
Intent intent = new Intent (StayActiveActivity.this, WebViewActivity.class);
StayActiveActivity.this.startActivity(intent);
}
}
});
AlertDialog alert = builder.create();
alert.show();
}}
WebViewActivity
package my.stayactive.plan;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebViewActivity extends StayActiveActivity {
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
webView = (WebView) findViewById(R.id.webView);
WebSettings setting = webView.getSettings();
setting.setJavaScriptEnabled(true);
if (url != null && url.length()>0) {
webView.loadUrl(url);
}
}
}
You didn't pass URL to your WebViewActivity. To do that:
Before calling startActivity(), attach your URL to the intent with setData().
In onCreate() of WebViewActivity, retrieve the URL with getData(), then load it.
Or search for putExtra(...). You can transfer a number of data with Intent.
— edited —
Example:
To set data:
import android.net.Uri;
//...
Intent intent = new Intent (StayActiveActivity.this, WebViewActivity.class);
intent.setData(Uri.parse("your-url"));
StayActiveActivity.this.startActivity(intent);
To retrieve data:
//...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//...
Uri uri = getIntent().getData();
//...
webView.loadUrl(uri.toString());
}
My guess is that your URLs are redirecting and that you aren't handling the redirects so nothing is being shown.
try adding this to your webview activity:
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return false;
}
});
Also it would be a good idea since you have an if statement in your WebView activity to log the url so that you can be certain that it is actually making it in to the activity correctly. If not the web view would never load anything.
EDIT: actually upon closer look it doesn't seem like you're setting the 'url' variable anywhere so it would be null, thus not calling your loadUrl method because of the if statement.

Categories

Resources