Google translation API problems on Android - java

I'm trying to use Google Translation API but I'm getting not null pointer error, this is the error:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.speakingtranslator.GoogleTranslateActivity.translte(java.lang.String, java.lang.String, java.lang.String)' on a null object reference
at com.example.speakingtranslator.MainActivity.translated(MainActivity.java:332)
at com.example.speakingtranslator.MainActivity$EnglishToTagalog.onPostExecute(MainActivity.java:310)
at com.example.speakingtranslator.MainActivity$EnglishToTagalog.onPostExecute(MainActivity.java:271)
Here is the code
public void translated() {
String translatetotagalog = editText.getText().toString();
Log.v("raw text",translatetotagalog);
String text = translator.translte(translatetotagalog, "en", "yo");
Log.v("translated text", text);
editTranslate.setText(text);
}
Here is the translte
String translte(String text, String from, String to) {
StringBuilder result = new StringBuilder();
try {
String encodedText = URLEncoder.encode(text, "UTF-8");
String urlStr = "https://www.googleapis.com/language/translate/v2?key="+ key +"&q=" + encodedText + "&target=" + to + "&source=" + from;
URL url = new URL(urlStr);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
InputStream stream;
if (conn.getResponseCode() == 200) //success
{
stream = conn.getInputStream();
} else
stream = conn.getErrorStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(result.toString());
if (element.isJsonObject()) {
JsonObject obj = element.getAsJsonObject();
if (obj.get("error") == null) {
String translatedText = obj.get("data").getAsJsonObject().
get("translations").getAsJsonArray().
get(0).getAsJsonObject().
get("translatedText").getAsString();
return translatedText;
}
}
if (conn.getResponseCode() != 200) {
System.err.println(result);
}
} catch (IOException | JsonSyntaxException ex) {
System.err.println(ex.getMessage());
}
return null;
}
Complete MainActivity.java
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.Settings;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import java.util.ArrayList;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
GoogleTranslateActivity translator;
private TextToSpeech textToSpeech;
private Button btn, button2, trans;
String soundName;
MediaPlayer mp = null;
String text2speak;
private boolean connected;
private static final String API_KEY = "API_KEY";
private EditText editText, editTranslate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
btn = findViewById(R.id.material_icon_button);
button2 = findViewById(R.id.material_icon_yoruba);
trans = findViewById(R.id.material_icon_translate);
checkPermission();
editText = findViewById(R.id.editText);
editTranslate = findViewById(R.id.editTranslate);
final SpeechRecognizer mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
final Intent mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,
Locale.getDefault());
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int ttsLang = textToSpeech.setLanguage(Locale.US);
if (ttsLang == TextToSpeech.LANG_MISSING_DATA
|| ttsLang == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "The Language is not supported!");
} else {
Log.i("TTS", "Language Supported.");
}
Log.i("TTS", "Initialization success.");
} else {
Toast.makeText(getApplicationContext(), "TTS Initialization failed!", Toast.LENGTH_SHORT).show();
}
}
});
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String data = editText.getText().toString();
Log.i("TTS", "button clicked: " + data);
int speechStatus = textToSpeech.speak(data, TextToSpeech.QUEUE_FLUSH, null);
if (speechStatus == TextToSpeech.ERROR) {
Log.e("TTS", "Error in converting Text to Speech!");
}
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
soundName = editTranslate.getText().toString();
soundName = soundName.replaceAll("\\s+", "_").toLowerCase();
SoundManager(soundName);
Toast.makeText(getApplicationContext(), soundName, Toast.LENGTH_LONG).show();
}
});
trans.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
text2speak = editText.getText().toString();
new EnglishToTagalog().execute();
}
});
mSpeechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle bundle) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float v) {
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int i) {
}
#Override
public void onResults(Bundle bundle) {
//getting all the matches
ArrayList<String> matches = bundle
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
//displaying the first match
if (matches != null)
editText.setText(matches.get(0));
}
#Override
public void onPartialResults(Bundle bundle) {
}
#Override
public void onEvent(int i, Bundle bundle) {
}
});
findViewById(R.id.material_icon_mic).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_UP:
mSpeechRecognizer.stopListening();
editText.setHint("You will see input here");
break;
case MotionEvent.ACTION_DOWN:
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
editText.setText("");
editText.setHint("Listening...");
break;
}
return false;
}
});
//Initialize and Assign Variable
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
//Set Home Selected
bottomNavigationView.setSelectedItemId(R.id.home);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.messages:
startActivity(new Intent(getApplicationContext(),Messages.class));
overridePendingTransition(0,0);
return true;
case R.id.home:
return true;
case R.id.info:
startActivity(new Intent(getApplicationContext(),Info.class));
overridePendingTransition(0,0);
return true;
}
return false;
}
});
}
private class EnglishToTagalog extends AsyncTask<Void, Void, Void> {
private ProgressDialog progress = null;
protected void onError(Exception ex) {
Toast.makeText(getApplicationContext(),ex.toString(), Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... params) {
try {
translator = new GoogleTranslateActivity(API_KEY);
Thread.sleep(15000);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPreExecute() {
// start the progress dialog
progress = ProgressDialog.show(MainActivity.this, null,
"Translating...");
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setIndeterminate(true);
super.onPreExecute();
}
#Override
protected void onPostExecute(Void result) {
translated();
progress.dismiss();
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
public void translated() {
String translatetotagalog = editText.getText().toString();
Toast.makeText(getApplicationContext(), translatetotagalog, Toast.LENGTH_LONG).show();
Log.v("raw text",translatetotagalog);
String text = translator.translte(translatetotagalog, "en", "yo");
//translatabletext = (TextView) findViewById(R.id.translatabletext);
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
Log.v("translated text", text);
editTranslate.setText(text);
}
protected void SoundManager(String sn){
if (mp != null){
mp.reset();
mp.release();
}
switch (sn){
case "e_kaaro":
mp = MediaPlayer.create(getApplicationContext(), R.raw.e_kaaro);
break;
case "e_kaasan":
mp = MediaPlayer.create(getApplicationContext(), R.raw.e_kaasan);
break;
case "e_kaale":
mp = MediaPlayer.create(getApplicationContext(), R.raw.e_kaale);
break;
case "bawo_ni_o_se_n_se":
mp = MediaPlayer.create(getApplicationContext(), R.raw.bawo_ni_o_se_n_se);
break;
case "mo_nife_re":
mp = MediaPlayer.create(getApplicationContext(), R.raw.mo_nife_re);
break;
default:
mp = MediaPlayer.create(getApplicationContext(), R.raw.crowd);
}
//Toast.makeText(getApplicationContext(), "clicked " + sn, Toast.LENGTH_LONG).show();
mp.start();
}
#Override
public void onDestroy() {
super.onDestroy();
if (textToSpeech != null) {
textToSpeech.stop();
textToSpeech.shutdown();
}
}
private void checkPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!(ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED)) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.parse("package:" + getPackageName()));
startActivity(intent);
finish();
}
}
}
public boolean checkInternetConnection() {
//Check internet connection:
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
//Means that we are connected to a network (mobile or wi-fi)
connected = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED;
return connected;
}
}

Related

android version 10 its work but android version 12 camera and gallery not working when download playstore

Android version 12 camera and gallery not working solution
I am working on a camera application with camera API. I am able to save the image to the picture directory and set it to the image view till android version 11 but on android 12, the image is getting saved to the picture directory but not getting set to the image view I am getting an error
My Code is
Profile.java
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import com.cocosw.bottomsheet.BottomSheet;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.databinding.DataBindingUtil;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xxx.xx.view.MainFragment;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
public class Profile extends AppCompatActivity implements View.OnClickListener {
private ActivityProfileBinding binding;
private String TAG = Profile.class.getSimpleName();
private Context mContext;
private ArrayList<ImageDTO> imageDatalist = new ArrayList<>();
private SharedPrefrence prefrence;
private LoginDTO loginDTO;
private HashMap<String, String> parms = new HashMap<>();
String dob = "";
String[] arrOfStr;
BottomSheet.Builder builder;
Uri picUri;
int PICK_FROM_CAMERA = 1, PICK_FROM_GALLERY = 2;
int CROP_CAMERA_IMAGE = 3, CROP_GALLERY_IMAGE = 4;
String imageName;
String pathOfImage;
Bitmap bm;
int flag = 1;
ImageCompression imageCompression;
byte[] resultByteArray;
File file;
Bitmap bitmap = null;
private HashMap<String, File> paramsFile = new HashMap<>();
HashMap<String, String> values = new HashMap<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_profile);
mContext = Profile.this;
prefrence = SharedPrefrence.getInstance(mContext);
loginDTO = prefrence.getLoginResponse(Consts.LOGIN_DTO);
parms.put(Consts.USER_ID, loginDTO.getUser_id());
values.put(Consts.USER_ID, loginDTO.getUser_id());
setUiaction();
}
public void setUiaction() {
binding.collapsingToolbar.setExpandedTitleColor(Color.TRANSPARENT);
binding.collapsingToolbar.setCollapsedTitleTextColor(Color.WHITE);
binding.collapsingToolbar.setTitle("Profile");
binding.rlBio.setOnClickListener(this);
binding.ivCamera.setOnClickListener(this);
binding.rlGallaryClick.setOnClickListener(this);
binding.back.setOnClickListener(this);
binding.ivEditSelf.setOnClickListener(this);
binding.ivEditAbout.setOnClickListener(this);
binding.ivEditAppearance.setOnClickListener(this);
binding.ivEditImportant.setOnClickListener(this);
binding.ivEditCritical.setOnClickListener(this);
binding.ivEditLifestyle.setOnClickListener(this);
binding.ivEditFamily.setOnClickListener(this);
builder = new BottomSheet.Builder(Profile.this).sheet(R.menu.menu_cards);
builder.title(getResources().getString(R.string.select_img));
builder.listener(new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case R.id.camera_cards:
if (ProjectUtils.hasPermissionInManifest(Profile.this, PICK_FROM_CAMERA, Manifest.permission.CAMERA)) {
if (ProjectUtils.hasPermissionInManifest(Profile.this, PICK_FROM_GALLERY, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
try {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = getOutputMediaFile(1);
if (!file.exists()) {
try {
ProjectUtils.pauseProgressDialog();
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//Uri contentUri = FileProvider.getUriForFile(getApplicationContext(), "com.example.asd", newFile);
picUri = FileProvider.getUriForFile(Profile.this.getApplicationContext(), Profile.this.getApplicationContext().getPackageName() + ".fileprovider", file);
} else {
picUri = Uri.fromFile(file); // create
}
prefrence.setValue(Consts.IMAGE_URI_CAMERA, picUri.toString());
intent.putExtra(MediaStore.EXTRA_OUTPUT, picUri); // set the image file
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (Exception e) {
e.printStackTrace();
}
}
}
break;
case R.id.gallery_cards:
if (ProjectUtils.hasPermissionInManifest(Profile.this, PICK_FROM_CAMERA, Manifest.permission.CAMERA)) {
if (ProjectUtils.hasPermissionInManifest(Profile.this, PICK_FROM_GALLERY, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
File file = getOutputMediaFile(1);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
picUri = Uri.fromFile(file);
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, getResources().getString(R.string.select_pic)), PICK_FROM_GALLERY);
}
}
break;
case R.id.cancel_cards:
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
dialog.dismiss();
}
});
break;
}
}
});
}
private File getOutputMediaFile(int type) {
String root = Environment.getExternalStorageDirectory().toString();
File mediaStorageDir = new File(root, Consts.APP_NAME);
/**Create the storage directory if it does not exist*/
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
/**Create a media file name*/
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == 1) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
Consts.APP_NAME + timeStamp + ".png");
imageName = Consts.APP_NAME + timeStamp + ".png";
} else {
return null;
}
return mediaFile;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CROP_CAMERA_IMAGE) {
if (data != null) {
picUri = Uri.parse(data.getExtras().getString("resultUri"));
try {
//bitmap = MediaStore.Images.Media.getBitmap(SaveDetailsActivityNew.this.getContentResolver(), resultUri);
pathOfImage = picUri.getPath();
imageCompression = new ImageCompression(Profile.this);
imageCompression.execute(pathOfImage);
imageCompression.setOnTaskFinishedEvent(new ImageCompression.AsyncResponse() {
#Override
public void processFinish(String imagePath) {
Glide.with(Profile.this).load("file://" + imagePath)
.thumbnail(0.5f)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(binding.ivProfileImage);
try {
// bitmap = MediaStore.Images.Media.getBitmap(SaveDetailsActivityNew.this.getContentResolver(), resultUri);
file = new File(imagePath);
paramsFile.put(Consts.USER_AVTAR, file);
Log.e("image", imagePath);
changeImage();
} catch (Exception e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
if (requestCode == CROP_GALLERY_IMAGE) {
if (data != null) {
picUri = Uri.parse(data.getExtras().getString("resultUri"));
try {
bm = MediaStore.Images.Media.getBitmap(Profile.this.getContentResolver(), picUri);
pathOfImage = picUri.getPath();
imageCompression = new ImageCompression(Profile.this);
imageCompression.execute(pathOfImage);
imageCompression.setOnTaskFinishedEvent(new ImageCompression.AsyncResponse() {
#Override
public void processFinish(String imagePath) {
Glide.with(Profile.this).load("file://" + imagePath)
.thumbnail(0.5f)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(binding.ivProfileImage);
try {
file = new File(imagePath);
paramsFile.put(Consts.USER_AVTAR, file);
changeImage();
Log.e("image", imagePath);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
if (requestCode == PICK_FROM_CAMERA && resultCode == RESULT_OK) {
if (picUri != null) {
picUri = Uri.parse(prefrence.getValue(Consts.IMAGE_URI_CAMERA));
startCropping(picUri, CROP_CAMERA_IMAGE);
} else {
picUri = Uri.parse(prefrence
.getValue(Consts.IMAGE_URI_CAMERA));
startCropping(picUri, CROP_CAMERA_IMAGE);
}
}
if (requestCode == PICK_FROM_GALLERY && resultCode == RESULT_OK) {
try {
Uri tempUri = data.getData();
Log.e("front tempUri", "" + tempUri);
if (tempUri != null) {
startCropping(tempUri, CROP_GALLERY_IMAGE);
} else {
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
public void startCropping(Uri uri, int requestCode) {
Intent intent = new Intent(Profile.this, MainFragment.class);
intent.putExtra("imageUri", uri.toString());
intent.putExtra("requestCode", requestCode);
startActivityForResult(intent, requestCode);
}
#Override
protected void onResume() {
super.onResume();
if (NetworkManager.isConnectToInternet(mContext)) {
getImages();
} else {
ProjectUtils.showToast(mContext, getResources().getString(R.string.internet_concation));
}
}
public void getImages() {
new HttpsRequest(Consts.GET_GALLARY_API, parms, mContext).stringPost(TAG, new Helper() {
#Override
public void backResponse(boolean flag, String msg, JSONObject response) {
getMyProfile();
if (flag) {
try {
imageDatalist = new ArrayList<>();
Type getpetDTO = new TypeToken<List<ImageDTO>>() {
}.getType();
imageDatalist = (ArrayList<ImageDTO>) new Gson().fromJson(response.getJSONArray("data").toString(), getpetDTO);
if (imageDatalist.size() > 0) {
} else {
imageDatalist = new ArrayList<>();
}
} catch (JSONException e) {
e.printStackTrace();
imageDatalist = new ArrayList<>();
}
} else {
imageDatalist = new ArrayList<>();
}
}
});
}
#Override
public void onBackPressed() {
//super.onBackPressed();
finish();
overridePendingTransition(R.anim.anim_slide_in_right,
R.anim.anim_slide_out_right);
}
public void getMyProfile() {
ProjectUtils.showProgressDialog(mContext, true, getResources().getString(R.string.please_wait));
new HttpsRequest(Consts.MY_PROFILE_API, getparmProfile(), mContext).stringPost(TAG, new Helper() {
#Override
public void backResponse(boolean flag, String msg, JSONObject response) {
if (flag) {
try {
loginDTO = new Gson().fromJson(response.getJSONObject("data").toString(), LoginDTO.class);
prefrence.setLoginResponse(loginDTO, Consts.LOGIN_DTO);
showData();
} catch (JSONException e) {
e.printStackTrace();
}
} else {
ProjectUtils.showToast(mContext, msg);
}
}
});
}
public HashMap<String, String> getparmProfile() {
HashMap<String, String> parms = new HashMap<>();
parms.put(Consts.USER_ID, loginDTO.getUser_id());
Log.e(TAG + " My Profile", parms.toString());
return parms;
}
public void changeImage() {
new HttpsRequest(Consts.SET_PROFILE_IMAGE_API, values,paramsFile, mContext).imagePost(TAG, new Helper() {
#Override
public void backResponse(boolean flag, String msg, JSONObject response) {
if (flag) {
getMyProfile();
} else {
}
}
});
}
}
MainFragment.java
import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.StringRes;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.appcompat.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import com.xxx.xx.R;
import com.isseiaoki.simplecropview.CropImageView;
import com.isseiaoki.simplecropview.callback.CropCallback;
import com.isseiaoki.simplecropview.callback.LoadCallback;
import com.isseiaoki.simplecropview.callback.SaveCallback;
import com.isseiaoki.simplecropview.util.Utils;
import java.io.File;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;
#RuntimePermissions
public class MainFragment extends FragmentActivity {
private static final int REQUEST_PICK_IMAGE = 10011;
private static final int REQUEST_SAF_PICK_IMAGE = 10012;
private static final String PROGRESS_DIALOG = "ProgressDialog";
Uri myUri;
int requestCode;
private CropImageView mCropView;
private LinearLayout mRootLayout;
public MainFragment() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
myUri = Uri.parse(getIntent().getExtras().getString("imageUri"));
requestCode = getIntent().getExtras().getInt("requestCode");
bindViews();
FontUtils.setFont(mRootLayout);
mCropView.startLoad(myUri, mLoadCallback);
mCropView.setCropMode(CropImageView.CropMode.FREE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent result) {
super.onActivityResult(requestCode, resultCode, result);
if (requestCode == REQUEST_PICK_IMAGE && resultCode == Activity.RESULT_OK) {
showProgress();
String uri = result.getData().toString();
mCropView.startLoad(result.getData(), mLoadCallback);
} else if (requestCode == REQUEST_SAF_PICK_IMAGE && resultCode == Activity.RESULT_OK) {
showProgress();
String uri = Utils.ensureUriPermission(this, result).toString();
mCropView.startLoad(Utils.ensureUriPermission(this, result), mLoadCallback);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
MainFragmentPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
}
private void bindViews() {
mCropView = (CropImageView) findViewById(R.id.cropImageView);
findViewById(R.id.buttonDone).setOnClickListener(btnListener);
findViewById(R.id.buttonFitImage).setOnClickListener(btnListener);
findViewById(R.id.button1_1).setOnClickListener(btnListener);
findViewById(R.id.button3_4).setOnClickListener(btnListener);
findViewById(R.id.button4_3).setOnClickListener(btnListener);
findViewById(R.id.button9_16).setOnClickListener(btnListener);
findViewById(R.id.button16_9).setOnClickListener(btnListener);
findViewById(R.id.buttonFree).setOnClickListener(btnListener);
findViewById(R.id.buttonPickImage).setOnClickListener(btnListener);
findViewById(R.id.buttonRotateLeft).setOnClickListener(btnListener);
findViewById(R.id.buttonRotateRight).setOnClickListener(btnListener);
findViewById(R.id.buttonCustom).setOnClickListener(btnListener);
findViewById(R.id.buttonCircle).setOnClickListener(btnListener);
findViewById(R.id.buttonShowCircleButCropAsSquare).setOnClickListener(btnListener);
mRootLayout = (LinearLayout) findViewById(R.id.layout_root);
}
#NeedsPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
public void pickImage() {
if (Build.VERSION.SDK_INT >= 33) {
startActivityForResult(new Intent(Intent.ACTION_GET_CONTENT).setType("image/*"), REQUEST_PICK_IMAGE);
} else {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_SAF_PICK_IMAGE);
}
}
#NeedsPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
public void cropImage() {
showProgress();
Log.e("cropImage", "called");
mCropView.startCrop(createSaveUri(), mCropCallback, mSaveCallback);
}
#OnShowRationale(Manifest.permission.READ_EXTERNAL_STORAGE)
public void showRationaleForPick(PermissionRequest request) {
showRationaleDialog(R.string.permission_pick_rationale, request);
}
#OnShowRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)
public void showRationaleForCrop(PermissionRequest request) {
showRationaleDialog(R.string.permission_crop_rationale, request);
}
public void showProgress() {
ProgressDialogFragment f = ProgressDialogFragment.getInstance();
getSupportFragmentManager()
.beginTransaction()
.add(f, PROGRESS_DIALOG)
.commitAllowingStateLoss();
}
public void dismissProgress() {
// if (!isAdded()) return;
FragmentManager manager = getSupportFragmentManager();
if (manager == null) return;
ProgressDialogFragment f = (ProgressDialogFragment) manager.findFragmentByTag(PROGRESS_DIALOG);
if (f != null) {
getSupportFragmentManager().beginTransaction().remove(f).commitAllowingStateLoss();
}
}
public Uri createSaveUri() {
return Uri.fromFile(new File(this.getCacheDir(), "cropped"));
}
private void showRationaleDialog(#StringRes int messageResId, final PermissionRequest request) {
new AlertDialog.Builder(this)
.setPositiveButton(R.string.button_allow, new DialogInterface.OnClickListener() {
#Override
public void onClick(#NonNull DialogInterface dialog, int which) {
request.proceed();
}
})
.setNegativeButton(R.string.button_deny, new DialogInterface.OnClickListener() {
#Override
public void onClick(#NonNull DialogInterface dialog, int which) {
request.cancel();
}
})
.setCancelable(false)
.setMessage(messageResId)
.show();
}
// Handle button event /////////////////////////////////////////////////////////////////////////
private final View.OnClickListener btnListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonDone:
MainFragmentPermissionsDispatcher.cropImageWithCheck(MainFragment.this);
break;
case R.id.buttonFitImage:
mCropView.setCropMode(CropImageView.CropMode.FIT_IMAGE);
break;
case R.id.button1_1:
mCropView.setCropMode(CropImageView.CropMode.SQUARE);
break;
case R.id.button3_4:
mCropView.setCropMode(CropImageView.CropMode.RATIO_3_4);
break;
case R.id.button4_3:
mCropView.setCropMode(CropImageView.CropMode.RATIO_4_3);
break;
case R.id.button9_16:
mCropView.setCropMode(CropImageView.CropMode.RATIO_9_16);
break;
case R.id.button16_9:
mCropView.setCropMode(CropImageView.CropMode.RATIO_16_9);
break;
case R.id.buttonCustom:
mCropView.setCustomRatio(7, 5);
break;
case R.id.buttonFree:
mCropView.setCropMode(CropImageView.CropMode.FREE);
break;
case R.id.buttonCircle:
mCropView.setCropMode(CropImageView.CropMode.CIRCLE);
break;
case R.id.buttonShowCircleButCropAsSquare:
mCropView.setCropMode(CropImageView.CropMode.CIRCLE_SQUARE);
break;
case R.id.buttonRotateLeft:
mCropView.rotateImage(CropImageView.RotateDegrees.ROTATE_M90D);
break;
case R.id.buttonRotateRight:
mCropView.rotateImage(CropImageView.RotateDegrees.ROTATE_90D);
break;
case R.id.buttonPickImage:
MainFragmentPermissionsDispatcher.pickImageWithCheck(MainFragment.this);
break;
}
}
};
// Callbacks ///////////////////////////////////////////////////////////////////////////////////
private final LoadCallback mLoadCallback = new LoadCallback() {
#Override
public void onSuccess() {
dismissProgress();
Log.e("", "success");
}
#Override
public void onError() {
dismissProgress();
Log.e("", "error");
}
};
private final CropCallback mCropCallback = new CropCallback() {
#Override
public void onSuccess(Bitmap cropped) {
}
#Override
public void onError() {
}
};
private final SaveCallback mSaveCallback = new SaveCallback() {
#Override
public void onSuccess(Uri outputUri) {
dismissProgress();
//addPicture.startResultActivity(outputUri);
Intent i = getIntent();
i.putExtra("resultUri", outputUri.toString());
setResult(requestCode, i);
finish();
}
#Override
public void onError() {
dismissProgress();
}
};
}
ProjectUtils.java
public static boolean hasPermissionInManifest(Context context, int requestCode, String permissionName) {
if (Build.VERSION.SDK_INT >= 29) {
Log.w(TAG, "hasPermissions: API version >= 29, returning true by default");
// DANGER ZONE!!! Changing this will break the library.
return true;
}
if (context == null) {
throw new IllegalArgumentException("Can't check permissions for null context");
}
if (ContextCompat.checkSelfPermission(context,
permissionName)
!= PackageManager.PERMISSION_GRANTED) {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions((Activity) context,
new String[]{permissionName},
requestCode);
} else {
return true;
}
return false;
}
AndroidManifest.java
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature
android:name="android.hardware.camera"
android:required="true" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="32"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="29"
tools:ignore="ScopedStorage" />
<!--Permission for the Android 11 and above-->
<queries>
<intent>
<action android:name="android.media.action.IMAGE_CAPTURE" />
</intent>
</queries>
<uses-permission android:name="android.permission.WRITE_SETTINGS"
tools:ignore="ProtectedPermissions" />
android:requestLegacyExternalStorage="true"
've also added requestLegacyExternalStorage="true" to the application tag in the manifest to get it to work for the APIs below Android 12. Stuck with this issue since yesterday, Please help.
Android version 12 camera and gallery not working solution

Attempt to invoke virtual method 'java.io.InputStream android.bluetooth.BluetoothSocket.getInputStream()'

I am trying to connect my android app with hc-06 for sending and receiving data purpose, below is the error occur and I've been stuck here from 3 days.
There error occured to me is
Attempt to invoke virtual method 'java.io.InputStreamandroid.bluetooth.BluetoothSocket.getInputStream()'
Kindly somebody solve it or provide me another working code for sending and receiving data through bluetoth hc-06 android app
package infoaryan.in.hc05_bluetooth;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
public class LedControl extends AppCompatActivity {
TextView textView;
Button btn1, btn2, btn3, btn4, btn5, btnDis;
String address = null;
TextView lumn;
private ProgressDialog progress;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
int counter;
volatile boolean stopWorker;
InputStream mmInputStream;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_led_control2);
Intent intent = getIntent();
address = intent.getStringExtra(MainActivity.EXTRA_ADDRESS);
btn1 = findViewById(R.id.button2);
btn2 = findViewById(R.id.button3);
//For additional actions to be performed
btn3 = findViewById(R.id.button5);
btn4 = findViewById(R.id.button6);
btn5 = findViewById(R.id.button7);
btnDis = findViewById(R.id.button4);
lumn = findViewById(R.id.textView2);
textView = findViewById(R.id.textView3);
new LedControl.ConnectBT().execute();
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
sendSignal("1");
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
sendSignal("0");
}
});
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
sendSignal("3");
}
});
btn4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
sendSignal("4");
}
});
btn5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
sendSignal("5");
}
});
btnDis.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
Disconnect();
}
});
beginListenForData();
}
private void sendSignal ( String givenumber ) {
if ( btSocket != null ) {
try {
btSocket.getOutputStream().write(givenumber.getBytes());
} catch (IOException e) {
msg("Error");
}
}
}
private void Disconnect () {
if ( btSocket!=null ) {
try {
btSocket.close();
} catch(IOException e) {
msg("Error");
}
}
finish();
}
private void msg (String s) {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
}
private class ConnectBT extends AsyncTask<Void, Void, Void> {
private boolean ConnectSuccess = true;
#Override
protected void onPreExecute () {
progress = ProgressDialog.show(LedControl.this, "Connecting...", "Please Wait!!!");
}
#Override
protected Void doInBackground (Void... devices) {
try {
if ( btSocket==null || !isBtConnected ) {
myBluetooth = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();
}
} catch (IOException e) {
ConnectSuccess = false;
}
return null;
}
#Override
protected void onPostExecute (Void result) {
super.onPostExecute(result);
if (!ConnectSuccess) {
msg("Connection Failed. Is it a SPP Bluetooth? Try again.");
finish();
} else {
msg("Connected");
isBtConnected = true;
}
progress.dismiss();
}
}
void beginListenForData()
{
final Handler handler = new Handler();
final byte delimiter = 10; //This is the ASCII code for a newline character
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable()
{
public void run()
{
while(!Thread.currentThread().isInterrupted() && !stopWorker)
{
try
{
int bytesAvailable = mmInputStream.available();
if(bytesAvailable > 0)
{
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for(int i=0;i<bytesAvailable;i++)
{
byte b = packetBytes[i];
if(b == delimiter)
{
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable()
{
public void run()
{
textView.setText(data);
}
});
}
else
{
readBuffer[readBufferPosition++] = b;
}
}
}
}
catch (IOException ex)
{
stopWorker = true;
}
}
}
});
workerThread.start();
}
#Override
protected void onResume() {
super.onResume();
}
}

Application has Stoppped (Android Studio Bluetooth)

I try to make communication between two devices by using Bluteooth but always the application stopped when i try to test it.
I just try to send simple string (for exemple 'A') but also I have errors.
Also i can't turn on/off bluetooth manually.
the error is : Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.bluetooth.BluetoothAdapter.isEnabled()' on a null object reference
at com.example.pfe.reglages.onCreate(reglages.java:53).
I need help because it's my project to get graduated
Thank you.
entrainement.java
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Handler;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
import android.os.Message;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import static android.bluetooth.BluetoothAdapter.getDefaultAdapter;
import static android.content.ContentValues.TAG;
public class entrainement extends AppCompatActivity {
private boolean CONTINUE_READ_WRITE = true;
private boolean CONNECTION_ENSTABLISHED = false;
private boolean DEVICES_IN_LIST = true;
private static String NAME = "pfe.fawez";
private static UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
Button btn6, btn7, btn8, btn16, btn9, btn5;
EditText txt;
TextView logview;
ListView lv;
ArrayList<String> listItems;
ArrayAdapter<String> listAdapter;
private BluetoothAdapter adapter;
private BluetoothSocket socket;
private InputStream is;
private OutputStream os;
private BluetoothDevice remoteDevice;
private Set<BluetoothDevice> pairedDevices;
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.entrainement);
btn6 = findViewById(R.id.button6);
btn7 = findViewById(R.id.button7);
btn8 = findViewById(R.id.button8);
btn16 = findViewById(R.id.button16);
btn9 = findViewById(R.id.button9);
btn5 = findViewById(R.id.button5);
txt = findViewById(R.id.editText2);
logview = findViewById(R.id.textView14);
lv = (ListView)findViewById(R.id.listView);
listItems = new ArrayList<String>(); //shows messages in list view
listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems);
lv.setAdapter(listAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() //list onclick selection process
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
if(DEVICES_IN_LIST)
{
String name = (String) parent.getItemAtPosition(position);
selectBTdevice(name); //selected device will be set globally
//Toast.makeText(getApplicationContext(), "Selected " + name, Toast.LENGTH_SHORT).show();
//do not automatically call OpenBT(null) because makes troubles with server/client selection
}
else //message is selected
{
String message = (String) parent.getItemAtPosition(position);
txt.setText(message);
}
}
/*adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter == null) //If the adapter is null, then Bluetooth is not supported
{
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_SHORT).show();
finish();
return;
}
list(null);*/
});
btn9.setOnClickListener(new View.OnClickListener() //sends text from text button
{
#Override
public void onClick(View v) {
String textToSend = txt.getText().toString();
byte[] b = textToSend.getBytes();
try {
os.write(b);
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Not sent", Toast.LENGTH_SHORT).show(); //usually problem server-client decision
}
logview.append("\nConnection !\n");
}
});
btn6.setOnClickListener(new View.OnClickListener() //sends text from text button
{
#Override
public void onClick(View v) {
String textToSend = "R";
byte[] b = textToSend.getBytes();
try {
os.write(b);
Toast.makeText(getApplicationContext(), "OK", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Not sent", Toast.LENGTH_SHORT).show(); //usually problem server-client decision
}
}
});
btn16.setOnClickListener(new View.OnClickListener() //sends text from text button
{
#Override
public void onClick(View v) {
String textToSend = "L";
byte[] b = textToSend.getBytes();
try {
os.write(b);
Toast.makeText(getApplicationContext(), "OK", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Not sent", Toast.LENGTH_SHORT).show(); //usually problem server-client decision
}
}
});
btn7.setOnClickListener(new View.OnClickListener() //sends text from text button
{
#Override
public void onClick(View v) {
String textToSend = "X";
byte[] b = textToSend.getBytes();
try {
os.write(b);
Toast.makeText(getApplicationContext(), "OK", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Not sent", Toast.LENGTH_SHORT).show(); //usually problem server-client decision
}
}
});
btn8.setOnClickListener(new View.OnClickListener() //sends text from text button
{
#Override
public void onClick(View v) {
String textToSend = "Y";
byte[] b = textToSend.getBytes();
try {
os.write(b);
Toast.makeText(getApplicationContext(), "OK", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Not sent", Toast.LENGTH_SHORT).show(); //usually problem server-client decision
}
}
});
}
private Runnable writter = new Runnable() {
#Override
public void run() {
while (CONTINUE_READ_WRITE) //reads from open stream
{
try
{
os.flush();
Thread.sleep(2000);
} catch (Exception e)
{
Log.e(TAG, "Writer failed in flushing output stream...");
CONTINUE_READ_WRITE = false;
}
}
}
};
public void list(View v) //shows paired devices to UI
{
CONNECTION_ENSTABLISHED = false; //protect from failing
listItems.clear(); //remove chat history
listAdapter.notifyDataSetChanged();
pairedDevices = adapter.getBondedDevices(); //list of devices
for(BluetoothDevice bt : pairedDevices) //foreach
{
listItems.add(0, bt.getName());
}
listAdapter.notifyDataSetChanged(); //reload UI
}
public void selectBTdevice(String name) //for selecting device from list which is used in procedures
{
if(pairedDevices.isEmpty()) {
list(null);
Toast.makeText(getApplicationContext(), "Selecting was unsucessful, no devices in list." ,Toast.LENGTH_SHORT ).show();
}
for(BluetoothDevice bt : pairedDevices) //foreach
{
if(name.equals(bt.getName()))
{
remoteDevice = bt;
Toast.makeText(getApplicationContext(), "Selected " + remoteDevice.getName(), Toast.LENGTH_SHORT ).show();
}
}
}
public void openBT(View v) //opens right thread for server or client
{
if(adapter == null)
{
adapter = getDefaultAdapter();
Log.i(TAG, "Backup way of getting adapter was used!");
}
CONTINUE_READ_WRITE = true; //writer tiebreaker
socket = null; //resetting if was used previously
is = null; //resetting if was used previously
os = null; //resetting if was used previously
if(pairedDevices.isEmpty() || remoteDevice == null)
{
Toast.makeText(this, "Paired device is not selected, choose one", Toast.LENGTH_SHORT).show();
return;
}
}
public void closeBT(View v) //for closing opened communications, cleaning used resources
{
/*if(adapter == null)
return;*/
CONTINUE_READ_WRITE = false;
CONNECTION_ENSTABLISHED = false;
if (is != null) {
try {is.close();} catch (Exception e) {}
is = null;
}
if (os != null) {
try {os.close();} catch (Exception e) {}
os = null;
}
if (socket != null) {
try {socket.close();} catch (Exception e) {}
socket = null;
}
try {
Handler mHandler = new Handler();
mHandler.removeCallbacksAndMessages(writter);
mHandler.removeCallbacksAndMessages(serverListener);
mHandler.removeCallbacksAndMessages(clientConnecter);
Log.i(TAG, "Threads ended...");
}catch (Exception e)
{
Log.e(TAG, "Attemp for closing threads was unsucessfull.");
}
Toast.makeText(getApplicationContext(), "Communication closed" ,Toast.LENGTH_SHORT).show();
list(null); //shows list for reselection
txt.setText(getResources().getString(R.string.demo));
}
private Runnable serverListener = new Runnable()
{
public void run()
{
try //opening of BT connection
{
android.util.Log.i("TrackingFlow", "Server socket: new way used...");
socket =(BluetoothSocket) remoteDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class}).invoke(remoteDevice,1);
socket.connect();
CONNECTION_ENSTABLISHED = true; //protect from failing
} catch(Exception e) //obsolete way how to open BT
{
try
{
android.util.Log.e("TrackingFlow", "Server socket: old way used...");
BluetoothServerSocket tmpsocket = adapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
socket = tmpsocket.accept();
CONNECTION_ENSTABLISHED = true; //protect from failing
android.util.Log.i("TrackingFlow", "Listening...");
}
catch (Exception ie)
{
Log.e(TAG, "Socket's accept method failed", ie);
ie.printStackTrace();
}
}
Log.i(TAG, "Server is ready for listening...");
runOnUiThread(new Runnable() {
#Override
public void run() { //Show message on UIThread
listItems.clear(); //remove chat history
listItems.add(0, String.format(" Server opened! Waiting for clients..."));
listAdapter.notifyDataSetChanged();
}});
try //reading part
{
is = socket.getInputStream();
os = socket.getOutputStream();
new Thread(writter).start();
int bufferSize = 1024;
int bytesRead = -1;
byte[] buffer = new byte[bufferSize];
while(CONTINUE_READ_WRITE) //Keep reading the messages while connection is open...
{
final StringBuilder sb = new StringBuilder();
bytesRead = is.read(buffer);
if (bytesRead != -1) {
String result = "";
while ((bytesRead == bufferSize) && (buffer[bufferSize-1] != 0))
{
result = result + new String(buffer, 0, bytesRead - 1);
bytesRead = is.read(buffer);
}
result = result + new String(buffer, 0, bytesRead - 1);
sb.append(result);
}
android.util.Log.e("TrackingFlow", "Read: " + sb.toString());
runOnUiThread(new Runnable() {
#Override
public void run() { //Show message on UIThread
Toast.makeText(entrainement.this, sb.toString(), Toast.LENGTH_SHORT).show();
listItems.add(0, String.format("< %s", sb.toString())); //showing in history
listAdapter.notifyDataSetChanged();
}
});
}
}
catch(IOException e){
Log.e(TAG, "Server not connected...");
e.printStackTrace();
}
}
};
private Runnable clientConnecter = new Runnable()
{
#Override
public void run()
{
try
{
socket = remoteDevice.createRfcommSocketToServiceRecord(MY_UUID);
socket.connect();
CONNECTION_ENSTABLISHED = true; //protect from failing
Log.i(TAG, "Client is connected...");
runOnUiThread(new Runnable() {
#Override
public void run() { //Show message on UIThread
listItems.clear(); //remove chat history
listItems.add(0, String.format(" ready to communicate! Write something..."));
listAdapter.notifyDataSetChanged();
}});
os = socket.getOutputStream();
is = socket.getInputStream();
new Thread(writter).start();
Log.i(TAG, "Preparation for reading was done");
int bufferSize = 1024;
int bytesRead = -1;
byte[] buffer = new byte[bufferSize];
while(CONTINUE_READ_WRITE) //Keep reading the messages while connection is open...
{
final StringBuilder sb = new StringBuilder();
bytesRead = is.read(buffer);
if (bytesRead != -1)
{
String result = "";
while ((bytesRead == bufferSize) && (buffer[bufferSize-1] != 0))
{
result = result + new String(buffer, 0, bytesRead - 1);
bytesRead = is.read(buffer);
}
result = result + new String(buffer, 0, bytesRead - 1);
sb.append(result);
}
android.util.Log.e("TrackingFlow", "Read: " + sb.toString());
runOnUiThread(new Runnable() {
#Override
public void run() { //Show message on UIThread
Toast.makeText(entrainement.this, sb.toString(), Toast.LENGTH_SHORT).show();
listItems.add(0, String.format("< %s", sb.toString()));
listAdapter.notifyDataSetChanged();
}
});
}
}
catch (IOException e)
{
Log.e(TAG, "Client not connected...");
e.printStackTrace();
}
}
};
}
reglages.java
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Set;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class reglages extends AppCompatActivity {
private static final int REQUEST_ENABLE_BT = 0;
private static final int REQUEST_DISCOVER_BT = 1;
TextView mStatusBlueTv, mPairedTv;
ImageView mBlueIv;
Button mOnBtn, mOffBtn, mDiscoverBtn, mPairedBtn;
BluetoothAdapter mBlueAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reglages);
mStatusBlueTv = findViewById(R.id.statusBluetoothTv);
mPairedTv = findViewById(R.id.pairedTv);
mBlueIv = findViewById(R.id.bluetoothIv);
mOnBtn = findViewById(R.id.onBtn);
mOffBtn = findViewById(R.id.offBtn);
mDiscoverBtn = findViewById(R.id.discoverableBtn);
mPairedBtn = findViewById(R.id.pairedBtn);
//adapter
mBlueAdapter = BluetoothAdapter.getDefaultAdapter();
//check if bluetooth is available or not
if (mBlueAdapter == null){
mStatusBlueTv.setText("Bluetooth is not available");
}
else {
mStatusBlueTv.setText("Bluetooth is available");
}
//set image according to bluetooth status(on/off)
if (mBlueAdapter.isEnabled()){
mBlueIv.setImageResource(R.drawable.ic_action_on);
}
else {
mBlueIv.setImageResource(R.drawable.ic_action_off);
}
//on btn click
mOnBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!mBlueAdapter.isEnabled()){
showToast("Turning On Bluetooth...");
//intent to on bluetooth
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, REQUEST_ENABLE_BT);
}
else {
showToast("Bluetooth is already on");
}
}
});
//discover bluetooth btn click
mDiscoverBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!mBlueAdapter.isDiscovering()){
showToast("Making Your Device Discoverable");
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(intent, REQUEST_DISCOVER_BT);
}
}
});
//off btn click
mOffBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mBlueAdapter.isEnabled()){
mBlueAdapter.disable();
showToast("Turning Bluetooth Off");
mBlueIv.setImageResource(R.drawable.ic_action_off);
}
else {
showToast("Bluetooth is already off");
}
}
});
//get paired devices btn click
mPairedBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mBlueAdapter.isEnabled()){
mPairedTv.setText("Paired Devices");
Set<BluetoothDevice> devices = mBlueAdapter.getBondedDevices();
for (BluetoothDevice device: devices){
mPairedTv.append("\nDevice: " + device.getName()+ ", " + device);
}
}
else {
//bluetooth is off so can't get paired devices
showToast("Turn on bluetooth to get paired devices");
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode){
case REQUEST_ENABLE_BT:
if (resultCode == RESULT_OK){
//bluetooth is on
mBlueIv.setImageResource(R.drawable.ic_action_on);
showToast("Bluetooth is on");
}
else {
//user denied to turn bluetooth on
showToast("could't on bluetooth");
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
//toast message function
private void showToast(String msg){
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
}
Then change this lines:
//check if bluetooth is available or not
if (mBlueAdapter == null){
mStatusBlueTv.setText("Bluetooth is not available");
}
else {
mStatusBlueTv.setText("Bluetooth is available");
}
//set image according to bluetooth status(on/off)
if (mBlueAdapter.isEnabled()){
mBlueIv.setImageResource(R.drawable.ic_action_on);
}
else {
mBlueIv.setImageResource(R.drawable.ic_action_off);
}
To this:
//check if bluetooth is available or not
if (mBlueAdapter == null) {
mStatusBlueTv.setText("Bluetooth is not available");
mBlueIv.setImageResource(R.drawable.ic_action_off);
} else {
mStatusBlueTv.setText("Bluetooth is available");
//set image according to bluetooth status(on/off)
if (mBlueAdapter.isEnabled()) {
mBlueIv.setImageResource(R.drawable.ic_action_on);
} else {
mBlueIv.setImageResource(R.drawable.ic_action_off);
}
}
And each time you check isEnabled check for null first, changing:
if (mBlueAdapter.isEnabled()){
to:
if (mBlueAdapter != null && mBlueAdapter.isEnabled()) {
This way you'll prevent having NullPointers when the Bluetooth is not available (mBlueAdapter == null) as you can not check isEnabled() in this cases.

Bluetooth communication in Android Cant get the message

I am trying to make a link (bluetooth) between my arduino and android. i want to recieve the data from the arduino. The ListenInput thread does get started but nothing more
Here is my code
package com.codeyard.teleprompter;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
public class bleutoothrevivedeletenow extends AppCompatActivity {
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
String address = null;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
Button StartConnection;
Button Disconnect;
Button Recieve;
TextView incomingData;
InputStream mmInStream = null;
String incomingMessage;
StringBuilder messages;
Thread ListenInput = new Thread() {
#Override
public void run() {
try {
mmInStream = btSocket.getInputStream();
byte[] buffer = new byte[1024];
int bytes;
Toast.makeText(getApplicationContext(), "Thread started///", Toast.LENGTH_LONG).show();
while (true) {
// Read from the InputStream
try {
if (mmInStream == null) {
Log.e("", "InputStream is null");
}
bytes = mmInStream.read(buffer);
incomingMessage = new String(buffer, 0, bytes);
messages.append(incomingMessage);
Toast.makeText(getApplicationContext(), "incoming message", Toast.LENGTH_LONG).show();
Toast.makeText(bleutoothrevivedeletenow.this, incomingMessage, Toast.LENGTH_LONG).show();
//TODO Remove this
} catch (Exception e) {
Toast.makeText(bleutoothrevivedeletenow.this, "128", Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
Toast.makeText(bleutoothrevivedeletenow.this, "133", Toast.LENGTH_SHORT).show();
}
}
};
private boolean isBtConnected = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bleutoothrevivedeletenow);
messages = new StringBuilder();
SharedPreferences sharedPreferences;
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(bleutoothrevivedeletenow.this);
address = sharedPreferences.getString("ADDRESS", "");
StartConnection = findViewById(R.id.button5);
Disconnect = findViewById(R.id.button6);
incomingData = findViewById(R.id.textView);
Recieve = findViewById(R.id.button7);
StartConnection.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new ConnectBT().execute();
}
});
Disconnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (btSocket != null) //If the btSocket is busy
{
try {
btSocket.close(); //close connection
} catch (IOException e) {
e.printStackTrace();
}
}
finish();
}
});
Recieve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ListenInput.start();
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
incomingData.setText(messages);
handler.postDelayed(this, 2000);
}
};
runnable.run();
}
});
}
private class ConnectBT extends AsyncTask<Void, Void, Void> // UI thread
{
private boolean ConnectSuccess = true; //if it's here, it's almost connected
#Override
protected void onPreExecute() {
Toast.makeText(getApplicationContext(), "Connecting....", Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
{
try {
if (btSocket == null || !isBtConnected) {
ActivityCompat.requestPermissions(bleutoothrevivedeletenow.this, new String[]{Manifest.permission.BLUETOOTH}, 1);
ActivityCompat.requestPermissions(bleutoothrevivedeletenow.this, new String[]{Manifest.permission.BLUETOOTH_ADMIN}, 1);
ActivityCompat.requestPermissions(bleutoothrevivedeletenow.this, new String[]{Manifest.permission.BLUETOOTH_PRIVILEGED}, 1);
myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);
//connects to the device's address and checks if it's available
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();//start connection
}
} catch (IOException e) {
ConnectSuccess = false;//if the try failed, you can check the exception here
}
return null;
}
#Override
protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
{
super.onPostExecute(result);
if (!ConnectSuccess) {
Toast.makeText(getApplicationContext(), "Connection Failed", Toast.LENGTH_SHORT).show();
finish();
} else {
Toast.makeText(getApplicationContext(), "Connection Successful", Toast.LENGTH_SHORT).show();
isBtConnected = true;
}
}
}
}
P.S. i have provided the entire code. this code is actually of this github repo:
https://github.com/IamMayankThakur/android-arduino-using-bluetooth
The code first genereated a IllegalThreadException but after debugging i edited the code and now it doesn't crash but still no incoming data

Updating the UI upon receiving an android push notification

I have a query regarding android push notification and i had asked it in another stackoverflow post and i did not get much help out of it [Query regarding Android push notifications. So i am posting it again, and it is as follows:
I have an android app that receives push notifications from Google push notification service. When i tap on the received notification, it opens an UI which displays this message, it is a list view. Now, when the user receives the push notification, and assuming that this screen is open, the UI should be refreshed automatically, such that it displays the latest notification. Could anybody let me know how i can solve this?
Below is my code that i have implemented:
Java code to receive the notification:
import java.util.Timer;
import java.util.TimerTask;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.util.Log;
import com.example.foodu.R;
import com.google.android.gcm.GCMBaseIntentService;
public class GCMIntentService extends GCMBaseIntentService {
private static final String TAG = "GCM ::Service";
// Use your PROJECT ID from Google API into SENDER_ID
public static final String SENDER_ID = "53340195486";
public GCMIntentService() {
super(SENDER_ID);
}
#Override
protected void onError(Context arg0, String errorId) {
Log.e(TAG, "onError: errorId=" + errorId);
}
#Override
protected void onMessage(Context context, Intent data) {
String message;
// Message from PHP server
message = data.getStringExtra("message");
// Open a new activity called GCMMessageView
Intent intent = new Intent(this, com.example.foodu.Notification.class);
// Pass data to the new activity
intent.putExtra("message", message);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Starts the activity on notification click
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
// Create the notification with a notification builder
Notification notification = new Notification.Builder(this)
.setSmallIcon(R.drawable.ic_logo)
.setWhen(System.currentTimeMillis())
.setContentTitle("Deals")
.setContentText(message).setContentIntent(pIntent)
.getNotification();
// Remove the notification on click
notification.flags |= Notification.FLAG_AUTO_CANCEL;
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(R.string.app_name, notification);
{
// Wake Android Device when notification received
PowerManager pm = (PowerManager) context
.getSystemService(Context.POWER_SERVICE);
final PowerManager.WakeLock mWakelock = pm.newWakeLock(
PowerManager.FULL_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP, "GCM_PUSH");
mWakelock.acquire();
// Timer before putting Android Device to sleep mode.
Timer timer = new Timer();
TimerTask task = new TimerTask() {
public void run() {
mWakelock.release();
}
};
timer.schedule(task, 5000);
}
}
#Override
protected void onRegistered(Context arg0, String registrationId) {
Log.i(TAG, "onRegistered: registrationId=" + registrationId);
}
#Override
protected void onUnregistered(Context arg0, String registrationId) {
Log.i(TAG, "onUnregistered: registrationId=" + registrationId);
}
}
The code for the corresponding activity that would be launched when the user taps on the notification:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.SimpleDateFormat;
import java.util.LinkedList;
import java.util.Locale;
import java.util.StringTokenizer;
import java.util.TimeZone;
import com.example.foodu.R;
import com.example.foodu.R.drawable;
import com.example.foodu.R.id;
import com.example.foodu.R.layout;
import com.example.foodu.R.menu;
import com.google.android.gcm.GCMRegistrar;
import android.support.v7.app.ActionBarActivity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.util.Log;
import android.view.ActionMode;
import android.view.ActionMode.Callback;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Notification extends ActionBarActivity {
LinkedList<NotificationData> notificationList = new LinkedList<NotificationData>();
ListView listView = null;
NotificationListAdapter adaptor;
ActionMode mActionMode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
overridePendingTransition(R.anim.trans_left_in, R.anim.trans_left_out);
listView = (ListView) findViewById(R.id.listView1);
// Retrive the data from GCMIntentService.java
Intent i = getIntent();
String message = i.getStringExtra("message");
//getDataForDisplay();
if(message!=null)
{
parseData(message);
}else{
getDataToDisplay();
}
adaptor = new NotificationListAdapter(getApplicationContext(), notificationList);
listView.setAdapter(adaptor);
TextView emptyText = (TextView) findViewById(R.id.empty);
emptyText.setText("No Events Yet!");
listView.setEmptyView(emptyText);
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
onListitemSelect(position);
view.setSelected(true);
return true;
}
});
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
adaptor.notifyDataSetChanged();
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
}
void writeToFile(){
FileOutputStream fos;
try {
fos = openFileOutput("varun", Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(notificationList);
oos.close();
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
void readFromFile(){
try{
FileInputStream fis = openFileInput("varun");
ObjectInputStream ois = new ObjectInputStream(fis);
LinkedList<NotificationData> local = (LinkedList<NotificationData>) ois.readObject();
ois.close();
for (int i = 0; i < local.size(); i++) {
notificationList.add(local.get(i));
}
}catch(Exception e){
e.printStackTrace();
}
}
private void getDataToDisplay() {
// TODO Auto-generated method stub
readFromFile();
}
private void parseData(String message) {
try {
int len = 0;
String[] stringArr = new String[100];
StringTokenizer st = new StringTokenizer(message, ".");
len = st.countTokens();
for (int i = 0; i < len; i++) {
if (st.hasMoreTokens()) {
stringArr[i] = st.nextToken();
}
}
NotificationData data = new NotificationData();
data.title = stringArr[0];
data.venue = stringArr[1];
data.date = stringArr[2];
data.time = stringArr[3];
notificationList.add(data);
readFromFile();
} catch (Exception e) {
e.printStackTrace();
}
}
private void getDateToDisplay() {
// TODO Auto-generated method stub
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
writeToFile();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.notificationmenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
if(id == R.id.action_register){
registerDevice();
return true;
}
return super.onOptionsItemSelected(item);
}
private void registerDevice() {
try {
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
GCMRegistrar
.register(Notification.this, GCMIntentService.SENDER_ID);
} catch (Exception e) {
e.printStackTrace();
}
}
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.notificationcontext, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_calender:
addToCalender();
mode.finish();
return true;
case R.id.menu_delete:
//deleteData();
showAlertBox();
return false;
case R.id.menu_share:
shareDate();
mode.finish();
return true;
case R.id.menu_copy:
copyToClip();
mode.finish();
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
adaptor.removeSelection();
}
};
void onListitemSelect(int position) {
adaptor.toggleSelection(position);
boolean hasCheckedItems = adaptor.getSelectedCount() > 0;
if (hasCheckedItems && mActionMode == null) {
mActionMode = startActionMode((Callback) mActionModeCallback);
} else if (!hasCheckedItems && mActionMode != null) {
mActionMode.finish();
}
if (mActionMode != null)
mActionMode.setTitle(String.valueOf(adaptor.getSelectedCount()));
}
protected void showAlertBox() {
// TODO Auto-generated method stub
AlertDialog.Builder builder1 = new AlertDialog.Builder(Notification.this);
builder1.setMessage("Delete " + adaptor.getSelectedIds().size()+ " events?");
builder1.setCancelable(true);
builder1.setIcon(R.drawable.alert);
builder1.setTitle("Caution");
builder1.setIcon(android.R.drawable.ic_dialog_alert);
builder1.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
deleteData();
mActionMode.finish();
}
});
builder1.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
protected void copyToClip() {
StringBuilder shareText = new StringBuilder();
for (int i = 0; i < adaptor.getSelectedIds().size(); i++) {
NotificationData data = notificationList
.get(adaptor.getSelectedIds().keyAt(i));
shareText.append(data.title + " " + data.venue + " " + data.date
+ " " + data.time);
shareText.append("\n");
}
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Notification App", shareText);
clipboard.setPrimaryClip(clip);
Toast.makeText(getApplicationContext(), "Data copied to ClipBoard",
Toast.LENGTH_LONG).show();
}
protected void shareDate() {
StringBuilder shareText = new StringBuilder();
for (int i = 0; i < adaptor.getSelectedIds().size(); i++) {
NotificationData data = notificationList
.get(adaptor.getSelectedIds().keyAt(i));
shareText.append(data.title + " " + data.venue + " " + data.date
+ " " + data.time);
shareText.append("\n");
}
String share = shareText.toString();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, share);
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
protected void deleteData() {
int count = 0;
int startPoint = adaptor.getSelectedIds().keyAt(0);
for (int i = 0; i < adaptor.getSelectedIds().size(); i++) {
adaptor.remove(notificationList.get(startPoint));
count++;
}
String message = " Event";
if(count>1)
{
message = " Events";
}
Toast.makeText(getApplicationContext(),
count + message+" deleted", Toast.LENGTH_LONG)
.show();
}
private void addToCalender() {
try {
int count = 0;
for (int i = 0; i < adaptor.getSelectedIds().size(); i++) {
NotificationData data = notificationList
.get(adaptor.getSelectedIds().keyAt(i));
ContentResolver cr = getApplicationContext()
.getContentResolver();
ContentValues values = new ContentValues();
String myDate = data.date + " " + data.time;
String timeArr[] = data.time.split("to");
SimpleDateFormat sfd = new SimpleDateFormat(
"' Date: 'MM/dd/yyyy 'Time: 'hh a", Locale.getDefault());
long time = sfd.parse(myDate).getTime();
values.put(CalendarContract.Events.DTSTART, time);
if (timeArr.length > 0) {
String endTime = timeArr[1];
SimpleDateFormat timeFormat = new SimpleDateFormat(
"' Date: 'MM/dd/yyyy hh a", Locale.getDefault());
long endtime = timeFormat.parse(data.date + " " + endTime)
.getTime();
values.put(CalendarContract.Events.DTEND, endtime);
}
values.put(CalendarContract.Events.TITLE, data.title);
values.put(CalendarContract.Events.DESCRIPTION, data.venue);
TimeZone timeZone = TimeZone.getDefault();
values.put(CalendarContract.Events.EVENT_TIMEZONE,
timeZone.getID());
values.put(CalendarContract.Events.CALENDAR_ID, 1);
Uri uri = cr
.insert(CalendarContract.Events.CONTENT_URI, values);
count++;
}
String message = " Event";
if(count>1)
{
message = " Events";
}
Toast.makeText(getApplicationContext(),
count + message + " added to Calender", Toast.LENGTH_LONG)
.show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Use LocalBroadcastManager
Check following code / steps
1) Add in your activity (UI refresh Activity)
private BroadcastReceiver mMyBroadcastReceiver;
Then ,
2) In onResume
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
mMyBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent)
{
// Here you can refresh your listview or other UI
Toast.makeText(getApplicationContext(), "Receiver", 2000).show();
}
};
try {
LocalBroadcastManager.getInstance(this).registerReceiver(mMyBroadcastReceiver,new IntentFilter("your_action"));
} catch (Exception e)
{
// TODO: handle exception
e.printStackTrace();
}}
// and your other code
3) Then unregister in onPause
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMyBroadcastReceiver);
}
4) Finally add in your GCM reciver class.
first check your activity is Visible or not using static variable
if visible add
Intent gcm_rec = new Intent("your_action"); LocalBroadcastManager.getInstance(arg0).sendBroadcast(gcm_rec);
else
use Notification Manager for notification.
I think this is easy and best way to refresh your listview UI / call Fetching method.

Categories