Import attribute values in the gimbal - attributes

Please inquire about the gimbal.
In the gimbal place in the getValue continue to occur NullPointerException.
code below.
placeEventListener = new PlaceEventListener() {
#Override
public void onVisitStart(Visit visit) {
String beaconName = visit.getPlace().getName();
try {
Toast.makeText(getApplicationContext(),
"KeyAll : " + visit.getPlace().getAttributes().getValue("X").toString(),
Toast.LENGTH_LONG).show();
}catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Err : " + e.toString(),
Toast.LENGTH_LONG).show();
};
beaconRegiste(beaconName);
}
#Override
public void onVisitEnd(Visit visit) {
Toast.makeText(getApplicationContext(),
"End of " + visit.getPlace().getName(),
Toast.LENGTH_SHORT).show();
}
};

Gimbal had the data internally. Therefore , Gimbal.resetApplicationInstanceIdentifier () the appropriate call were hayeoseo success .

Related

I can't show up the captured image in the thumbnails

its a class assignment and I need to finish it today.
So basically the captured image is saved but it won't show up in the imgVpic imageview camera open up and the image captured is saved correctly with the correct file name but it just won't show up in the thumbnail that I set up, I checked in the gallery and the picture is there but again .. the image won't show in this imgVpic image view (i kept repeating this cause I can't post this question without "more details" since my post is mostly code, pls help I'm a student and I hate my teacher)
here is the code that I used
public class CaptureImgActivity extends AppCompatActivity {
final int CAMERA_RESULT=0;
Uri imgUri=null;
Button btTakePic;
ImageView imgVPic;
private void CaptureImageUri(){
String dir= Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM).getAbsolutePath();
File folder=new File(dir + File.separator+"test");
boolean success=true;
if (!folder.exists()){
try {
success=folder.mkdir();
Toast.makeText(this,"Folder Create Successfull", Toast.LENGTH_SHORT).show();
}catch (Exception e){
success = !success;
e.printStackTrace();
}
}
if (success){
dir=dir+ File.separator+"test";
}
Calendar calendar=Calendar.getInstance();
File file= new File(dir,"test"+(calendar.getTimeInMillis()+".jpg"));
if (!file.exists()){
try {
file.createNewFile();
imgUri= FileProvider.getUriForFile(CaptureImgActivity.this,BuildConfig.APPLICATION_ID,file);
Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,imgUri);
startActivityForResult(intent,CAMERA_RESULT);
}catch (Exception e){
e.printStackTrace();
}
}else {
try {
file.delete();
file.createNewFile();
imgUri= FileProvider.getUriForFile(CaptureImgActivity.this,BuildConfig.APPLICATION_ID,file);
Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,imgUri);
startActivityForResult(intent,CAMERA_RESULT);
}catch (Exception e){
e.printStackTrace();
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == CAMERA_RESULT && requestCode == RESULT_OK){
try {
Uri imgUri=data.getData();
Bitmap bitmap= MediaStore.Images.Media.getBitmap(this.getContentResolver(),imgUri);
imgVPic.setImageBitmap(bitmap);
}catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_capture_img);
btTakePic = (Button) findViewById(R.id.btTakePic);
imgVPic = (ImageView) findViewById(R.id.imgVPic);
btTakePic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CaptureImageUri();
}
});
}
}
I tried in both method like choose image from gallery and Capture Image by adding
android:requestLegacyExternalStorage="true"
My Code is Different from yours but work as the same process but this works for me
Uri imgUri=null;
protected static final int CAMERA_REQUEST = 0;
protected static final int GALLERY_PICTURE = 1;
private Intent pictureActionIntent = null;
Bitmap bitmap;
String selectedImagePath;
private void SelectImage() {
AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(
getActivity());
myAlertDialog.setTitle("Upload Pictures Option");
myAlertDialog.setMessage("How do you want to set your picture?");
myAlertDialog.setPositiveButton("Gallery",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Intent pictureActionIntent = null;
pictureActionIntent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(
pictureActionIntent,
GALLERY_PICTURE);
}
});
myAlertDialog.setNegativeButton("Camera",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
imgUri= FileProvider.getUriForFile(Objects.requireNonNull(getContext()), BuildConfig.APPLICATION_ID + ".provider", file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
startActivityForResult(intent, CAMERA_REQUEST);
}
});
myAlertDialog.show();
}
OnActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
bitmap = null;
selectedImagePath = null;
if (resultCode == RESULT_OK && requestCode == CAMERA_REQUEST) {
File f = new File(Environment.getExternalStorageDirectory()
.toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
if (!f.exists()) {
Toast.makeText(getContext(), "Error while capturing image", Toast.LENGTH_LONG).show();
return;
}
try {
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath());
bitmap = Bitmap.createScaledBitmap(bitmap, 400, 400, true);
int rotate = 0;
try {
ExifInterface exif = new ExifInterface(f.getAbsolutePath());
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
}
} catch (Exception e) {
e.printStackTrace();
}
Matrix matrix = new Matrix();
matrix.postRotate(rotate);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), matrix, true);
mImageView.setImageBitmap(bitmap);
//storeImageTosdCard(bitmap);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (resultCode == RESULT_OK && requestCode == GALLERY_PICTURE) {
if (data != null) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getActivity().getContentResolver().query(selectedImage, filePath,
null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
selectedImagePath = c.getString(columnIndex);
c.close();
bitmap = BitmapFactory.decodeFile(selectedImagePath); // load
mImageView.setImageBitmap(bitmap);
} else {
Toast.makeText(getContext(), "Cancelled",
Toast.LENGTH_SHORT).show();
}
}
}
And both method works for me and displayed thumbnail

update instant message in conversation activity - Android

I am building an instant messaging feature in my app using retrofit 2.0,php and mysql. But i do not know how to show and update the messages received and send in the recyclerview.
conversation Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_conversation);
dp=findViewById(R.id.conversationUser);
back=findViewById(R.id.goBackFromCoversation);
name=findViewById(R.id.conversationUserName);
activeStatus=findViewById(R.id.conversationUserSeen);
shareTitle=findViewById(R.id.conversationStatusTitle);
typeMessage=findViewById(R.id.typeMessage);
attach=findViewById(R.id.attachFiles);
send=findViewById(R.id.sendMessage);
recyclerView=findViewById(R.id.conversationRv);
toolbar=findViewById(R.id.converationToolbar);
setSupportActionBar(toolbar);
if (SharedPrefManager.getInstance(this).contains("keyid")) {
id = SharedPrefManager.getInstance(this).getUser().getId();
Toast.makeText(this, "user id is " + id, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "no id found", Toast.LENGTH_SHORT).show();
}
getUserId= getIntent().getIntExtra("userId",0);
getUserName=getIntent().getStringExtra("userName");
getUserDp=getIntent().getStringExtra("dpUrl");
chatType=getIntent().getIntExtra("chatType",0);
if(getUserDp==null){
Toast.makeText(getApplicationContext(),"user dp is null, value is "+getUserDp,Toast.LENGTH_SHORT).show();
}else {
loadDp(getUserDp);
}
name.setText(getUserName);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
((LinearLayoutManager) mLayoutManager).setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setNestedScrollingEnabled(true);
fetchConversation(id,getUserId);
cla=new ConversationAdapter(this,conversation);
recyclerView.setAdapter(cla);
back.setOnClickListener(this);
name.setOnClickListener(this);
attach.setOnClickListener(this);
send.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.goBackFromCoversation:
finish();
break;
case R.id.conversationUserName:
Intent intent= new Intent(ConversationActivity.this,ViewProfileActivity.class);
intent.putExtra("userId",getUserId);
startActivity(intent);
break;
case R.id.attachFiles:
break;
case R.id.sendMessage:
getTextMessage=typeMessage.getText().toString();
messageType=0;
sendMessage(chatType,id,getUserId,messageType,getTextMessage);
onCreate(null);
break;
}
}
private void fetchConversation(int id, int getUserId) {
Gson gson = new GsonBuilder()
.setLenient()
.create();
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor).build();
Retrofit retrofi = new Retrofit.Builder()
.baseUrl("http://192.168.56.110/app2/")
.addConverterFactory(GsonConverterFactory.create(gson))
.addConverterFactory(ScalarsConverterFactory.create())
.client(client)
.build();
RetrofitApi service = retrofi.create(RetrofitApi.class);
Call<Message> call = service.getMessages(id,getUserId);
/* Call<Message> call = RetrofitClient
.getmInstance()
.getApi()
.getMessages(id, Integer.parseInt(getUserId));*/
call.enqueue(new Callback<Message>() {
#Override
public void onResponse(Call<Message> call, Response<Message> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
Message sr = response.body();
int count=sr.getConversation().toArray().length;
if(sr.getSuccess()==1){
for(int i=0;i<sr.getConversation().toArray().length;i++){
messageId=sr.getConversation().get(i).getMessageId();
fromId=sr.getConversation().get(i).getSenderId();
toId=sr.getConversation().get(i).getReceiverId();
type=sr.getConversation().get(i).getType();
timeSent=sr.getConversation().get(i).getTime_sent();
message=sr.getConversation().get(i).getMessage();
Conversation c=new Conversation(messageId,fromId,toId,type,message,timeSent);
conversation.add(c);
cla.notifyDataSetChanged();
}
}else{
Log.v(TAG,"success is not 1");
}
} else {
Log.v(TAG, "fetchConvo, response is null ");
Toast.makeText(getApplicationContext(), "resposne is null", Toast.LENGTH_SHORT).show();
}
} else {
Log.v(TAG, "fetchConvo, Something went wrong");
Toast.makeText(getApplicationContext(), "Something went wrong- ", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<Message> call, Throwable t) {
Log.v(TAG, "fetchConvo, response is" + t.getMessage());
Toast.makeText(getApplicationContext(), "Failure, response is- " + t.getMessage(), Toast.LENGTH_LONG).show();
Log.v(TAG, "fetchConvo, Failed, cause is " + t.getCause());
Toast.makeText(getApplicationContext(), "Failed, cause is - " + t.getCause(), Toast.LENGTH_LONG).show();
}
});
}
private void loadDp(String getUserDp) {
String[] parts= getUserDp.split("htdocs");
String newString="http://192.168.56.110"+ parts[1];
Log.e(TAG, newString );
GlideApp.with(this).
load(newString)
.diskCacheStrategy( DiskCacheStrategy.ALL )
.into(dp);
}
private void sendMessage(int chat,int id, int getUserId, int messageType, String getTextMessage) {
Log.v(TAG,"id is"+ id);
Log.v(TAG,"userId is"+ getUserId);
Log.v(TAG,"type is"+ messageType);
Log.v(TAG,"message is"+getTextMessage);
Gson gson = new GsonBuilder()
.setLenient()
.create();
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor).build();
Retrofit retrofi = new Retrofit.Builder()
.baseUrl("http://192.168.56.110/app2/")
.addConverterFactory(GsonConverterFactory.create(gson))
.addConverterFactory(ScalarsConverterFactory.create())
.client(client)
.build();
RetrofitApi service = retrofi.create(RetrofitApi.class);
Call<com.example.user.myapplication.Model.Response> call = service.saveMessages(id,getUserId,getTextMessage,messageType);
/* Call<com.example.user.myapplication.Model.Response> call = RetrofitClient
.getmInstance()
.getApi()
.saveMessages(id,getUserId,getTextMessage,messageType);*/
call.enqueue(new Callback<com.example.user.myapplication.Model.Response>() {
#Override
public void onResponse(Call<com.example.user.myapplication.Model.Response> call, Response<com.example.user.myapplication.Model.Response> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
com.example.user.myapplication.Model.Response sr = response.body();
if(sr.getSuccess()==1){
Log.v(TAG,"Response is successful");
}
} else {
Log.v(TAG, "saveMessage, response is null ");
Toast.makeText(getApplicationContext(), "resposne is null", Toast.LENGTH_SHORT).show();
}
} else {
Log.v(TAG, "saveMessage, Something went wrong");
Toast.makeText(getApplicationContext(), "Something went wrong- ", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<com.example.user.myapplication.Model.Response> call, Throwable t) {
Log.v(TAG, "saveMessage, response is" + t.getMessage());
Toast.makeText(getApplicationContext(), "Failure, response is- " + t.getMessage(), Toast.LENGTH_LONG).show();
Log.v(TAG, "saveMessage, Failed, cause is " + t.getCause());
Toast.makeText(getApplicationContext(), "Failed, cause is - " + t.getCause(), Toast.LENGTH_LONG).show();
}
});
}
Conversation Adapter
public class ConversationAdapter extends RecyclerView.Adapter<ConversationAdapter.ViewHolder> {
private static final String TAG = "ChatListAdapter";
private Context context;
private ArrayList<Conversation> conversation= new ArrayList<>();
private int id;
public ConversationAdapter(Context context, ArrayList<Conversation> conversation) {
this.context = context;
this.conversation = conversation;
}
#NonNull
#Override
public ConversationAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item_message, viewGroup, false);
ConversationAdapter.ViewHolder viewHolder = new ConversationAdapter.ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i) {
if (SharedPrefManager.getInstance(context).contains("keyid")) {
id = SharedPrefManager.getInstance(context).getUser().getId();
Toast.makeText(context, "user id is " + id, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "no id found", Toast.LENGTH_SHORT).show();
}
if(Integer.parseInt(conversation.get(i).getSenderId())==id){
viewHolder.messageSent.setText(conversation.get(i).getMessage());
viewHolder.messaegReceievd.setVisibility(View.GONE);
}else{
viewHolder.messaegReceievd.setText(conversation.get(i).getMessage());
viewHolder.messageSent.setVisibility(View.GONE);
}
if(i==conversation.toArray().length-1) {
viewHolder.messageTime.setText(conversation.get(conversation.toArray().length- 1).getTime_sent());
}else{
viewHolder.messageTime.setVisibility(View.GONE);
}
}
#Override
public int getItemCount() {
return conversation.toArray().length;
}
public class ViewHolder extends RecyclerView.ViewHolder {
BubbleTextView messageSent,messaegReceievd;
TextView messageTime;
public ViewHolder(#NonNull View itemView) {
super(itemView);
Log.v(TAG, "ViewHolder, setting view in variables");
messageSent=itemView.findViewById(R.id.textMessageSent);
messaegReceievd=itemView.findViewById(R.id.textMessageReceived);
messageTime=itemView.findViewById(R.id.messageSentTime);
}
}
}
Whenever i send message and tries to reload the activity to show the messages received or send i start activity again and have to make network request once again which i think will take much time when real user will use it. So, therefore i want to implement something else to make it instant messaging activity.
Any help would be appreciated Thanks in advance

Zebra label printer in Mono for Android causes unexpected crash with no exceptions

I have created a Mono for Android application which uses the Zebra printing API. I have managed to get the ZSDK_API.jar file referenced in both a Java Bindings Library and a Standard Mono for Android application as defined HERE
I have added the .jar file to the JBL project (Jars folder) and set it's build action to InputJar
I also added the jar to the Mono for Android application with the build action set to AndroidJavaLibrary.
DiscoveryHandler
public class DiscoveryHandler : IDiscoveryHandler
{
private Discovery _reference;
public DiscoveryHandler(Discovery reference)
{
_reference = reference;
}
public void DiscoveryError(string message)
{
new UIHelper(_reference).showErrorDialogOnGuiThread(message);
}
public void DiscoveryFinished()
{
_reference.RunOnUiThread(() =>
{
Toast.MakeText(_reference, " Discovered " + _reference.discoveredPrinters.Count + " devices", ToastLength.Short).Show();
_reference.SetProgressBarIndeterminateVisibility(false);
});
}
public void FoundPrinter(DiscoveredPrinter printer)
{
_reference.RunOnUiThread(() =>
{
DiscoveredPrinterBluetooth p = (DiscoveredPrinterBluetooth)printer;
_reference.discoveredPrinters.Add(p.Address + " (" + p.FriendlyName + ")");
_reference.mArrayAdapter.NotifyDataSetChanged();
});
}
public void Dispose()
{
}
public IntPtr Handle
{
get { return _reference.Handle; }
}
}
Discovery.cs
public class Discovery : ListActivity
{
public List<string> discoveredPrinters = null;
public ArrayAdapter<string> mArrayAdapter;
private static IDiscoveryHandler btDiscoveryHandler = null;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
RequestWindowFeature(WindowFeatures.IndeterminateProgress);
SetContentView(Resource.Layout.discovery_results);
SetProgressBarIndeterminateVisibility(true);
discoveredPrinters = new List<string>();
SetupListAdapter();
btDiscoveryHandler = new DiscoveryHandler(this);
try
{
new Thread(new ThreadStart(() =>
{
Looper.Prepare();
try
{
RunOnUiThread(() => Toast.MakeText(this, "Trying", ToastLength.Short).Show());
BluetoothDiscoverer.FindPrinters(this, btDiscoveryHandler);
RunOnUiThread(() => Toast.MakeText(this, "And...", ToastLength.Short).Show());
}
catch (ZebraPrinterConnectionException zex)
{
new UIHelper(this).showErrorDialogOnGuiThread(zex.Message);
}
catch (ThreadInterruptedException iex)
{
new UIHelper(this).showErrorDialogOnGuiThread(iex.Message);
}
catch (Exception ex)
{
new UIHelper(this).showErrorDialogOnGuiThread(ex.Message);
}
finally
{
RunOnUiThread(() => Toast.MakeText(this, "Quitting looper", ToastLength.Short).Show());
Looper.MyLooper().Quit();
RunOnUiThread(() => Toast.MakeText(this, "Finished", ToastLength.Short).Show());
}
})).Start();
}
catch (Exception ex)
{
new UIHelper(this).showErrorDialogOnGuiThread(ex.Message);
}
}
private void SetupListAdapter()
{
mArrayAdapter = new ArrayAdapter<string>(this, global::Android.Resource.Layout.SimpleListItem1, discoveredPrinters);
ListAdapter = mArrayAdapter;
}
}
I have made sure the manifest is requesting Bluetooth and Bluetooth_Admin as well as internet.
The application builds, but when run simply crashes, no exception and just says "The Application Has Stopped Unexpectedly"
All the classes are being detected and compiled, but I have no idea why it is bombing like this. Has anyone succeeded with a Mono for Android - Zebra integration?
Dammit - I am a chop! Just as I posted it I got to thinking - it probably has something to do with the fact that I was implementing IntPtr Handle as the parent's handle - I was right. Here is the first step of working code (FIRST STEP - if I have to answer my own questions!):
public class Discovery : ListActivity, IDiscoveryHandler
{
public List<string> discoveredPrinters = null;
public ArrayAdapter<string> mArrayAdapter;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
RequestWindowFeature(WindowFeatures.IndeterminateProgress);
SetContentView(Resource.Layout.discovery_results);
SetProgressBarIndeterminateVisibility(true);
discoveredPrinters = new List<string>();
SetupListAdapter();
try
{
new Thread(new ThreadStart(() =>
{
Looper.Prepare();
try
{
BluetoothDiscoverer.FindPrinters(this, this);
}
catch (ZebraPrinterConnectionException zex)
{
new UIHelper(this).showErrorDialogOnGuiThread(zex.Message);
}
catch (ThreadInterruptedException iex)
{
new UIHelper(this).showErrorDialogOnGuiThread(iex.Message);
}
catch (Exception ex)
{
new UIHelper(this).showErrorDialogOnGuiThread(ex.Message);
}
finally
{
RunOnUiThread(() => Toast.MakeText(this, "Quitting looper", ToastLength.Short).Show());
Looper.MyLooper().Quit();
RunOnUiThread(() => Toast.MakeText(this, "Finished", ToastLength.Short).Show());
}
})).Start();
}
catch (Exception ex)
{
new UIHelper(this).showErrorDialogOnGuiThread(ex.Message);
}
}
private void SetupListAdapter()
{
mArrayAdapter = new ArrayAdapter<string>(this, global::Android.Resource.Layout.SimpleListItem1, discoveredPrinters);
ListAdapter = mArrayAdapter;
}
public void DiscoveryError(string message)
{
new UIHelper(this).showErrorDialogOnGuiThread(message);
}
public void DiscoveryFinished()
{
RunOnUiThread(() =>
{
Toast.MakeText(this, " Discovered " + discoveredPrinters.Count + " devices", ToastLength.Short).Show();
SetProgressBarIndeterminateVisibility(false);
});
}
public void FoundPrinter(DiscoveredPrinter printer)
{
RunOnUiThread(() =>
{
DiscoveredPrinterBluetooth p = printer.JavaCast<DiscoveredPrinterBluetooth>();
discoveredPrinters.Add(p.Address + " (" + p.FriendlyName + ")");
mArrayAdapter.NotifyDataSetChanged();
});
}
}
}

How to enable a button after 5 seconds

everyone! I need to make a Button disabled for 5 seconds, and the caption of the button must be "Skip" plus the time the button will stay disabled.
I have made a class CTimer that extends Thread, and defined the run method with run(Button). The run method receives the Button which Caption will be modified and is as follows:
public void run(Button skip){
for ( int i=5; i<0; i--)
{
skip.setText("Skip (" + i + ")");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
skip.setEnabled(true);
}
The problem is that the code does not work, any thouhts, anyone?
I have tried the following code & it works fine for me:
public class Main_TestProject extends Activity
{
private Button b;
private int index = 5;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b = (Button) findViewById(R.id.my_button);
b.setEnabled(false);
hHandler.sendEmptyMessage(0);
}
private Handler hHandler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
if(index > 0)
{
try
{
b.setText("Skip (" + String.valueOf(index) + ")");
index--;
Thread.sleep(1000);
hHandler.sendEmptyMessage(0);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
b.setEnabled(true);
}
}
};
}

J2ME SMS IOException

I am trying to send a text message to a phone and I get an error
Fail to send because of unknown reason. -java.io.IOException
import javax.microedition.io.Connector;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Form;
import javax.microedition.midlet.*;
import javax.wireless.messaging.MessageConnection;
import javax.wireless.messaging.TextMessage;
public class Midlet extends MIDlet {
Form form = new Form("Form");
Display display;
public void startApp()
{
display = Display.getDisplay(this);
display.setCurrent(form);
sendSMS("Hello from j2me");
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
private void sendSMS(String s) {
String destination = "+12234567890";
String addr = "sms://" + destination;
out("Setting up message");
MessageConnection sender = null;
try
{
try
{
sender = (MessageConnection) Connector.open(addr);
TextMessage msg = (TextMessage) sender.newMessage(MessageConnection.TEXT_MESSAGE);
msg.setPayloadText(s);
out("sending");
sender.send(msg);
out("sent successfully");
}
catch (Exception ex)
{
out("Error1:" + ex.getMessage() + " : " + ex.toString() + "\n\n");
}
finally
{
sender.close();
}
}
catch (Exception ex) {
//handle exception
out("Error2:" + ex.getMessage() + " : " + ex.toString() + "\n\n");
}
}
private void out(String str)
{
form.append(str + "\n");
}
}
Did you add permissions to your jad?
MIDlet-Permissions: javax.microedition.io.Connector.sms,javax.wireless.messaging.sms.send
All sorts of reasons:
No credit on PAYG phone
No mobile reception
SMS API blocked by handset operator
User rejected security prompt (this would cause a SecurityException)
Invalid mobile number

Resources