Continously updating marker on running Google Map v2 - sms

I am making a tracking app that receive data(longitude and latitude) from the user via SMS and display on the googlemapv2. I want my application to work continously and the marker update on new location when a new message is received.But the marker doesn't move to new location.
I have made 2 java files. One is "IncomingSms" that receives new SMS and other is "MainActivity" that display google map and show marker.It show marker on defaultposition but don't update on new coordinates.
Please help me...here is my code..
package com.example.chck;
public class MainActivity extends Activity {
public static LatLng point;
GoogleMap gMap;
#Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
Log.d("Activity","Got new Data again");
Toast.makeText(getApplicationContext(),"In NEW-INTENT", Toast.LENGTH_SHORT).show();
initializeMap();
drawMarker();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.MyMap)).getMap();
initializeMap();
Toast.makeText(getApplicationContext(),"In CREATE", Toast.LENGTH_SHORT).show();
// Enabling MyLocation Layer of Google Map
gMap.setMyLocationEnabled(true);
}
private void drawMarker(){
// Clears all the existing coordinates
String LON="72.99056966";
String LAT="33.64272895";
gMap.clear();
if(IncomingSms.chk==1){
Intent i1 = getIntent();
LAT = i1.getExtras().getString("NewLat");
LON = i1.getExtras().getString("NewLon");
}
Toast.makeText(getBaseContext(),LAT + LON , Toast.LENGTH_SHORT).show();
point = new LatLng(Double.parseDouble(LAT), Double.parseDouble(LON));
// Creating an instance of MarkerOptions
MarkerOptions markerOptions = new MarkerOptions();
// Setting latitude and longitude for the marker
gMap.clear();
markerOptions.position(point);
// Setting title for the InfoWindow
markerOptions.title("Position");
// Setting InfoWindow contents
markerOptions.snippet("Latitude:"+point.latitude+",Longitude"+point.longitude);
// Adding marker on the Google Map
gMap.addMarker(markerOptions);
// Moving CameraPosition to the user input coordinates
gMap.moveCamera(CameraUpdateFactory.newLatLng(point));
}
private void initializeMap() {
if (gMap == null) {
gMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.MyMap)).getMap();
// check if map is created successfully or not
if (gMap == null)
Toast.makeText(getApplicationContext(),"Sorry! unable to create maps", Toast.LENGTH_SHORT).show();
}
}
#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;
}
}
========================
IncomingSms.java
package com.example.chck;
public class IncomingSms extends BroadcastReceiver {
public static double latitude;
public static double longitude;
public static int chk =0;
public static String la;
public static String lo;
// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage
.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage
.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
String[] columns = message.split(",");
assert columns.length == 2;
longitude = Double.parseDouble(columns[0]);
latitude = Double.parseDouble(columns[1]);
la= columns[1];
lo= columns[0];
Log.i("SmsReceiver", "senderNum: " + senderNum
+ "; message: " + message);
int duration = Toast.LENGTH_LONG;
//Toast toast = Toast.makeText(context, "Latitude: "+
//longitude + ", Longitude: " + latitude, duration);
//toast.show();
} // end for loop
chk=1;
//New Location fetched
Toast.makeText(context,la + lo , Toast.LENGTH_SHORT).show();
final Intent i1 = new Intent(context, MainActivity.class);
i1.putExtra("NewLat", la);
i1.putExtra("NewLon", lo);
int duration1 = Toast.LENGTH_LONG;
//Toast toast1 = Toast.makeText(context, "Check Latitude: "+
// lo + ", Longitude: " + la, duration1);
//toast1.show();
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" + e);
}
}
}

Related

How About onActivityResult when I want to read multiple file from storage

How About onActivityResult when I want to read multiple file form storage
In this xml form I have to take multiple image file by clicking different different button from the app external storage but their is a difficulties on ActivityResult override method calling , because it call automatically and can't be call multiple time for for different different button
It's working fine for single file picking and get image URI.
So how can I fix the ActivityResult override method for different different button in a single activity
public class Application_Form extends AppCompatActivity {
ActivityApplicationBinding binding;
boolean isOnlyImageAllowed = true;
private static final int PICK_PHOTO = 1958;
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityApplicationBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
//check user storage permission
int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
this,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
binding.form4.choosePropertyFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent;
if (isOnlyImageAllowed) {
// only image can be selected
intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
} else {
// any type of files including image can be selected
intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
}
startActivityForResult(intent, PICK_PHOTO);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_PHOTO) {
Uri imageUri = data.getData();
binding.form4.selectedPropertyFile.setText("" + imageUri.getLastPathSegment());
}
}
}
Taking a array to pick photo then check with if else statement by array index
public class Application_Form extends AppCompatActivity {
ActivityApplicationBinding binding;
boolean isOnlyImageAllowed = true;
private static int[] PICK_PHOTO={0,1,2,3,4,5} ;
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityApplicationBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
binding.appBar.title.setText("লাইসেন্সের জন্য আবেদন করুন");
binding.appBar.back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
//check user storage permission
int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
this,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
binding.form4.choosePropertyFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent;
if (isOnlyImageAllowed) {
// only image can be selected
intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
} else {
// any type of files including image can be selected
intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
}
startActivityForResult(intent, 0);
}
});
binding.form4.chooseBankCertificate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent;
if (isOnlyImageAllowed) {
// only image can be selected
intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
} else {
// any type of files including image can be selected
intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
}
startActivityForResult(intent, 1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_PHOTO[0]) {
Uri imageUri = data.getData();
binding.form4.selectedPropertyFile.setText("" + imageUri.getLastPathSegment());
}
if (resultCode == RESULT_OK && requestCode == PICK_PHOTO[1]) {
Uri imageUri = data.getData();
binding.form4.selectedBankCertificate.setText("" + imageUri.getLastPathSegment());
}
}
}

Recyclerview adapter with asyncTask

I'm trying to use custom adapter with RecyclerView, but the holders are empty. I can't understand what did i miss. Please help.
In MainActivity's AsyncTask:
#Override
protected void onPostExecute(String result) {
json_result = result;
super.onPostExecute(result);
dialog.dismiss();
if (result == null) {
Toast.makeText(MainActivity.this, "error getting results...", Toast.LENGTH_LONG).show();
} else {
try {
JSONObject json = new JSONObject(result);
Log.e(TAG, "create json object");
JSONArray searchArray = json.getJSONArray("Search");
Log.e(TAG, "Search");
for (int i = 0; i < searchArray.length(); i++) {
Log.e(TAG, "run on length");
JSONObject searchObject = searchArray.getJSONObject(i);
Log.e(TAG, "create search object");
String title = searchObject.getString("Title");
Log.e(TAG, "Title" + title);
String type = searchObject.getString("Type");
Log.e(TAG, "Type" + type);
String year = searchObject.getString("Year");
Log.e(TAG, "Year" + year);
String imdbID = searchObject.getString("imdbID");
String poster = searchObject.getString("Poster");
Log.e(TAG, "" + result);
movieList.add(new Movie(title, type, year, imdbID, poster));
Log.e(TAG, "Add to adapter");
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "error parsing results...", Toast.LENGTH_LONG).show();
}
adapter.notifyDataSetChanged();
Log.e(TAG, "Notify");
}
}
Custom Adapter:
public class Adapter extends
RecyclerView.Adapter<Adapter.ViewHolder> {
private LruCache<String, Bitmap> bitmapCache;
Context context;
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public TextView year;
public TextView type;
public ImageView poster;
public ViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.txt_title);
year = (TextView) itemView.findViewById(R.id.txt_year);
type = (TextView) itemView.findViewById(R.id.txt_rating);
poster = (ImageView) itemView.findViewById(R.id.imageView);
}
}
private List<Movie> mList;
public Adapter(List<Movie> mList) {
this.mList = mList;
int numImages = 4 * 1024 * 1024;
this.bitmapCache = new LruCache<String, Bitmap>(numImages) {
#Override
protected int sizeOf(String key, Bitmap value) {
// this is how to calculate a bitmap size in bytes.
// (bytes-in-a-row * height)
return value.getRowBytes() * value.getHeight();
}
};
}
#Override
public Adapter.ViewHolder onCreateViewHolder
(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View movieView = inflater.inflate(R.layout.card_view, parent, false);
ViewHolder viewHolder = new ViewHolder(movieView);
return viewHolder;
}
#Override
public void onBindViewHolder
(Adapter.ViewHolder holder, int position) {
Movie movie = mList.get(position);
holder.title.setText(movie.getTitle());
holder.year.setText(movie.getYear());
holder.type.setText(movie.getType());
holder.poster.setVisibility(View.INVISIBLE);
GetImageTask task = new GetImageTask(movie, holder);
task.execute(movie.getPoster_url());
}
#Override
public int getItemCount() {
return mList.size();
}
class GetImageTask extends AsyncTask<String, Void, Bitmap> {
private final Movie movie;
private final ViewHolder holder;
public GetImageTask(Movie movie, ViewHolder holder) {
this.movie = movie;
this.holder = holder;
}
#Override
protected Bitmap doInBackground(String... params) {
//download:
String address = params[0];
Bitmap bitmap = HttpHandler.getBitmap(address, null);
//save it in the cache for later:
if (bitmap != null) {
bitmapCache.put(address, bitmap);
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
if (movie.equals(holder.poster)) {
holder.poster.setVisibility(View.VISIBLE);
holder.poster.setImageBitmap(result);
}
}
}
}
I think the problem is that my movie class is empty, but i do have JSON results in asynctask...
Your received data , which you have saved in the list -->movieList.
Have you used it in your adapter and set the adapter to the recycler view.
Initialize recycler view in main class
initialize adapter and pass the movielist as arguement to the adapter object created.
attach the adapter to the recyclerview --> recyclerView.setAdapter(adapter).
I think this should work

GUI JFrame background color change

I've revisited this post. I have been able to upload the text file, create a GUI, populate the GUI with JRadioButtons that are labeled from the text file...
Now, I cannot get the background to change color when the JRadioButton is selected! I know that it has something to do with the ActionListener, but how do I fix this? The color needs to be implemented from the hex color code.
public class FP extends JFrame implements ActionListener {
TreeMap<String, String> buttonMap = new TreeMap <>();
// Constructor
#SuppressWarnings("empty-statement")
public FP() throws IOException {
JPanel panel = new JPanel();
add(panel, BorderLayout.CENTER);
panel.setBorder(new TitledBorder("Pick a Radio Button!"));
JRadioButton[] btnArray = new JRadioButton[20];
ButtonGroup btnGroup = new ButtonGroup();
BufferedReader reader;
reader = new BufferedReader(new FileReader("src/colors.txt"));
String currentLine = reader.readLine();
while (currentLine != null) {
String[] pair = currentLine.split("\\s+");
buttonMap.put(pair[0],pair[1]);
currentLine = reader.readLine();
}
//check retrieving values from the buttonMap
for(Map.Entry<String,String> entry : buttonMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
}
for (int i = 0; i<20; i++){
for(Map.Entry<String, String> entry : buttonMap.entrySet()){
JRadioButton rb = new JRadioButton(entry.getKey() + " " + entry.getValue());
panel.add(rb);
btnGroup.add(rb);
rb.addActionListener(this);
}
}
//private final JRadioButton btnMale = new JRadioButton("Male")
Collection bMapIt = buttonMap.entrySet();
Iterator it = bMapIt.iterator();
System.out.println("Colors and codes");
while(it.hasNext())
System.out.println(it.next());
}
#Override
public void actionPerformed(ActionEvent e) {
setBackground(Color.decode(buttonMap.get(e)));
}
public static void main(String[] args) throws IOException {
FP frame = new FP();
frame.setVisible(true);
frame.setSize(350, 240);
frame.setTitle("Final Project");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
for(Map.Entry<String, String> entry : buttonMap.entrySet()){
for (int i = 0; i<1; i++){
btnArray[i] = new JRadioButton(entry.getKey() + " " + entry.getValue());
panel.add(btnArray[i]);
btnGroup.add(btnArray[i]);
btnArray[i].addActionListener((ActionEvent e) -> {
String btnColor = buttonMap.get(((JRadioButton) e.getSource()).getText());
String hexColor = entry.getValue();
System.out.println(hexColor);
panel.setBackground(Color.decode("#"+hexColor));
});
}
}
This with the addition of class....
#Override
public void actionPerformed(ActionEvent e) {}
}

How to save Image captured from camera in gallery as well as in backup folder

In My application I am capturing image from camera and storing it in folder created by me. This folder is getting created in Pictures. Now I wants to save same image in my local storages's /BackUp folder.
This is code for
public class MainActivity extends Activity {
// Activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private MultipartEntity multipartEntity;
// directory name to store captured images and videos
private static final String IMAGE_DIRECTORY_NAME = "FORMS";
private Bitmap bitmap1;
private Uri fileUri; // file url to store image/video
private static String output;
private ImageView imgPreview;
private VideoView videoPreview;
private Button btnCapturePicture, btnRecordVideo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgPreview = (ImageView) findViewById(R.id.imgPreview);
videoPreview = (VideoView) findViewById(R.id.videoPreview);
btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
btnRecordVideo = (Button) findViewById(R.id.btnRecordVideo);
/*
* Capture image button click event
*/
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// capture picture
captureImage();
}
});
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
}
private void previewCapturedImage() {
try {
imgPreview.setVisibility(View.VISIBLE);
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
imgPreview.setImageBitmap(bitmap1);
//imgPreview.setImageBitmap(result);
} catch (NullPointerException e) {
e.printStackTrace();
}
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
}
return mediaFile;
}
Right Now this image is getting save at PICTURES/FORMS Folder. I wants to save it to FORMSBACKUP/IMAGES Folder as well.

Black Berry Table View

here is my app. how to add table view or grids in the following.
should i draw every thing plz help
this is my code
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.system.*;
import net.rim.device.api.util.*;
import java.util.*;
/*An application in which user enters the data. this data is displayed when user press the save button*/
public class Display extends UiApplication {
/*declaring Strings to store the data of the user*/
String getFirstName;
String getLastName;
String getEmail;
String getGender;
String getStatus;
/*declaring text fields for user input*/
private AutoTextEditField firstName;
private AutoTextEditField lastName;
private EmailAddressEditField email;
/*declaring choice field for user input*/
private ObjectChoiceField gender;
/*declaring check box field for user input*/
private CheckboxField status;
//Declaring button fields
private ButtonField save;
private ButtonField close;
private ButtonField List;
/*declaring vector*/
private static Vector _data;
/*declaring persistent object*/
private static PersistentObject store;
/*creating an entry point*/
public static void main(String[] args)
{
Display obj = new Display();
obj.enterEventDispatcher();
}
/*creating default constructor*/
public Display()
{
/*Creating an object of the main screen class to use its functionalities*/
MainScreen mainScreen = new MainScreen();
//setting title of the main screen
mainScreen.setTitle(new LabelField("Enter Your Data"));
//creating text fields for user input
firstName = new AutoTextEditField("First Name: ", "");
lastName= new AutoTextEditField("Last Name: ", "");
email= new EmailAddressEditField("Email:: ", "");
//creating choice field for user input
String [] items = {"Male","Female"};
gender= new ObjectChoiceField("Gender",items);
//creating Check box field
status = new CheckboxField("Active",true);
//creating Button fields and adding functionality using listeners
save = new ButtonField("Save",ButtonField.CONSUME_CLICK);
save.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
save();
}
});
close = new ButtonField("Close",ButtonField.CONSUME_CLICK);
close.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
onClose();
}
});
List = new ButtonField("List",ButtonField.CONSUME_CLICK);
List.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context){
pushScreen(new ListScreen());
}
});
//adding the input fields to the main screen
mainScreen.add(firstName);
mainScreen.add(lastName);
mainScreen.add(email);
mainScreen.add(gender);
mainScreen.add(status);
//adding buttons to the main screen
HorizontalFieldManager horizontal = new HorizontalFieldManager(HorizontalFieldManager.FIELD_HCENTER);
horizontal.add(close);
horizontal.add(save);
horizontal.add(List);
mainScreen.add(horizontal);
//adding menu items
mainScreen.addMenuItem(saveItem);
mainScreen.addMenuItem(getItem);
mainScreen.addMenuItem(Deleteall);
//pushing the main screen
pushScreen(mainScreen);
}
private MenuItem Deleteall = new MenuItem("Delete all",110,10)
{
public void run()
{
int response = Dialog.ask(Dialog.D_YES_NO,"Are u sure u want to delete entire Database");
if(Dialog.YES == response){
PersistentStore.destroyPersistentObject(0xdec6a67096f833cL);
onClose();
}
else
Dialog.inform("Thank God");
}
};
//adding functionality to menu item "saveItem"
private MenuItem saveItem = new MenuItem("Save", 110, 10)
{
public void run()
{
//Calling save method
save();
}
};
//adding functionality to menu item "saveItem"
private MenuItem getItem = new MenuItem("Get", 110, 11)
{
//running thread for this menu item
public void run()
{
//synchronizing thread
synchronized (store)
{
//getting contents of the persistent object
_data = (Vector) store.getContents();
try{
for (int i = _data.size()-1; i >-1; i--)
{
StoreInfo info = (StoreInfo)_data.elementAt(i);
//checking for empty object
if (!_data.isEmpty())
{
//if not empty
//create a new object of Store Info class
//storing information retrieved in strings
getFirstName = (info.getElement(StoreInfo.NAME));
getLastName = (info.getElement(StoreInfo.LastNAME));
getEmail = (info.getElement(StoreInfo.EMail));
getGender = (info.getElement(StoreInfo.GenDer));
getStatus = (info.getElement(StoreInfo.setStatus));
//calling the show method
show();
}
}
}
catch(Exception e){}
}
}
};
public void save()
{
//creating an object of inner class StoreInfo
StoreInfo info = new StoreInfo();
//getting the test entered in the input fields
info.setElement(StoreInfo.NAME, firstName.getText());
info.setElement(StoreInfo.LastNAME,lastName.getText());
info.setElement(StoreInfo.EMail, email.getText());
info.setElement(StoreInfo.GenDer,gender.toString());
if(status.getChecked())
info.setElement(StoreInfo.setStatus, "Active");
else
info.setElement(StoreInfo.setStatus, "In Active");
//adding the object to the end of the vector
_data.addElement(info);
//synchronizing the thread
synchronized (store)
{
store.setContents(_data);
store.commit();
}
//resetting the input fields
Dialog.inform("Success!");
firstName.setText(null);
lastName.setText(null);
email.setText("");
gender.setSelectedIndex("Male");
status.setChecked(true);
}
//coding for persistent store
static {
store =
PersistentStore.getPersistentObject(0xdec6a67096f833cL);
synchronized (store) {
if (store.getContents() == null) {
store.setContents(new Vector());
store.commit();
}
}
_data = new Vector();
_data = (Vector) store.getContents();
}
//new class store info implementing persistable
private static final class StoreInfo implements Persistable
{
//declaring variables
private Vector _elements;
public static final int NAME = 0;
public static final int LastNAME = 1;
public static final int EMail= 2;
public static final int GenDer = 3;
public static final int setStatus = 4;
public StoreInfo()
{
_elements = new Vector(5);
for (int i = 0; i < _elements.capacity(); ++i)
{
_elements.addElement(new String(""));
}
}
public String getElement(int id)
{
return (String) _elements.elementAt(id);
}
public void setElement(int id, String value)
{
_elements.setElementAt(value, id);
}
}
//details for show method
public void show()
{
Dialog.alert("Name is "+getFirstName+" "+getLastName+"\nGender is "+getGender+"\nE-mail: "+getEmail+"\nStatus is "+getStatus);
}
public void list()
{
Dialog.alert("haha");
}
//creating save method
//overriding onClose method
public boolean onClose()
{
System.exit(0);
return true;
}
class ListScreen extends MainScreen
{
String firstUserName="Ali";
String lastUserName="Asif";
String userEmail="assad";
String userGender="asdasd";
String userStatus="active";
private AutoTextEditField userFirstName;
private AutoTextEditField userLastName;
private EmailAddressEditField userMail;
private ObjectChoiceField usersGender;
private CheckboxField usersStatus;
private ButtonField btnBack;
public ListScreen()
{
SeparatorField sps = new SeparatorField();
HorizontalFieldManager hr = new HorizontalFieldManager(HorizontalFieldManager.FIELD_HCENTER|HorizontalFieldManager.HORIZONTAL_SCROLLBAR);
VerticalFieldManager vr = new VerticalFieldManager();
setTitle(new LabelField("List of All Data"));
list();
btnBack = new ButtonField("Back",ButtonField.CONSUME_CLICK);
btnBack.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field,int context)
{
UiApplication.getUiApplication().popScreen(getScreen());
}
});
hr.add(btnBack);
add(hr);
add(sps);
}
public void list()
{
_data = (Vector) store.getContents();
try{
int sn=0;
for (int i = _data.size()-1; i >-1; i--,sn++)
{
StoreInfo info = (StoreInfo)_data.elementAt(i);
//checking for empty object
if (!_data.isEmpty())
{
//if not empty
//create a new object of Store Info class
//storing information retrieved in strings
firstUserName = (info.getElement(StoreInfo.NAME));
lastUserName = (info.getElement(StoreInfo.LastNAME));
userEmail = (info.getElement(StoreInfo.EMail));
userGender = (info.getElement(StoreInfo.GenDer));
userStatus = (info.getElement(StoreInfo.setStatus));
//calling the listAll method
listAll();
}
}
}
catch(Exception e){}
}
public void listAll()
{
SeparatorField sp = new SeparatorField();
SeparatorField sps = new SeparatorField();
HorizontalFieldManager hrs = new HorizontalFieldManager(HorizontalFieldManager.HORIZONTAL_SCROLL);
hrs.add(new RichTextField(""+firstUserName+" "+lastUserName+" | "+userEmail+" | "+userGender+" | "+userStatus));
//add(new RichTextField("Email: "+userEmail));
//add(new RichTextField("Gender: "+userGender));
//add(new RichTextField("Status: "+userStatus));
//SeparatorField sp = new SeparatorField();
add(hrs);
add(sp);
add(sps);
}
public boolean onClose()
{
System.exit(0);
return true;
}
}
}
There is a nice GridFieldManager by Anthony Rizk.
Code:
public void list()
{
if (null != mGrid && null != mGrid.getManager())
mGrid.getManager().delete(mGrid);
int colWidth = net.rim.device.api.system.Display.getWidth() / 4;
mGrid = new GridFieldManager(new int[] { 0, colWidth, colWidth,
colWidth, colWidth }, VERTICAL_SCROLL | VERTICAL_SCROLLBAR);
mGrid.add(new NullField(FOCUSABLE));
mGrid.add(new LabelField("Name"));
mGrid.add(new LabelField("E-Mail"));
mGrid.add(new LabelField("Gender"));
mGrid.add(new LabelField("Active"));
add(mGrid);
_data = (Vector) store.getContents();
try {
int sn = 0;
for (int i = _data.size() - 1; i > -1; i--, sn++) {
StoreInfo info = (StoreInfo) _data.elementAt(i);
// checking for empty object
if (!_data.isEmpty()) {
// if not empty
// create a new object of Store Info class
// storing information retrieved in strings
firstUserName = (info.getElement(StoreInfo.NAME));
lastUserName = (info.getElement(StoreInfo.LastNAME));
userEmail = (info.getElement(StoreInfo.EMail));
userGender = (info.getElement(StoreInfo.GenDer));
userStatus = (info.getElement(StoreInfo.setStatus));
// calling the listAll method
mGrid.add(new NullField(FOCUSABLE));
mGrid.add(new LabelField(firstUserName + " "
+ lastUserName));
mGrid.add(new LabelField(userEmail));
mGrid.add(new LabelField(userGender));
mGrid.add(new LabelField(userStatus));
}
}
} catch (Exception e) {
}
}
See also
BlackBerry Grid Layout Manager updated

Resources