Getting Error java.lang.IllegalArgumentException: unexpected url - java

Hi i am trying to send some data to server by using json parsing but activity is getting crashed and it leads to
java.lang.IllegalArgumentException: unexpected url
This is My Activity Code and i am commenting the lines where i am getting the Errors.
public class LoginActivity extends AppCompatActivity { **// Showing Error at this LIne**
public Location location;
private Button btnLogin;
private boolean doubleBackToExitPressedOnce = false;
private EditText phoneNo, password;
private CheckBox cbShow, cbRemember;
private NetworkUtil networkUtil;
private SharePrefUtil sharePref;
private LocationInfo locationInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
networkUtil = new NetworkUtil(getApplicationContext());
sharePref = new SharePrefUtil(getApplicationContext());
initScreen();
if (sharePref.getValueFromSharePref("remeberFlag").equalsIgnoreCase("true")) {
phoneNo.setText(sharePref.getValueFromSharePref("mobileno"));
password.setText(sharePref.getValueFromSharePref("password"));
cbRemember.setChecked(true);
}
}
private void initScreen() {
LocationLibrary.showDebugOutput(true);
try {
LocationLibrary.initialiseLibrary(LoginActivity.this, 60 * 1000, 60 * 1000 * 2, "com.aspeage.jagteraho");
} catch (UnsupportedOperationException e) {
Toast.makeText(this, "Device doesn't have any location providers", Toast.LENGTH_LONG).show();
}
phoneNo = (EditText) findViewById(R.id.ed_phoneno);
password = (EditText) findViewById(R.id.ed_password);
cbRemember = (CheckBox) findViewById(R.id.cbox_rememberme);
cbRemember.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) sharePref.setValueInSharePref("remeberFlag", "true");
else sharePref.setValueInSharePref("remeberFlag", "false");
}
});
cbShow = (CheckBox) findViewById(R.id.cbox_showpass);
cbShow.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
} else {
password.setInputType(129);
}
}
});
btnLogin = (Button) findViewById(R.id.btn_login);
btnLogin.setOnClickListener(new ButtonClick());
}
private class ButtonClick implements View.OnClickListener {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_login:
btnLoginClicked();
break;
default:
break;
}
}
}
private void btnLoginClicked() {
if(phoneNo.getText().toString().trim().equals("admin") && password.getText().toString().trim().equals("admin")) {
loginService();
}
if (validation()) {
if (cbRemember.isChecked())
rememberMe(password.getText().toString().trim());
if (networkUtil.isConnected()) {
loginService();
} else {
new SweetAlertDialog(LoginActivity.this, cn.pedant.SweetAlert.SweetAlertDialog.ERROR_TYPE)
.setTitleText("Oops...")
.setContentText("No Network Connection")
.show();
}
}
}
/**
* save username and password in SharedPreferences.
*
* #param //password is key value for storing in SharedPreferences.
*/
public void rememberMe(String password) {
SharePrefUtil sharePref = new SharePrefUtil(getApplicationContext());
sharePref.setValueInSharePref("password", password);
}
private boolean validation() {
int errorCount = 0;
if (phoneNo.getText().toString().trim().equals("")
|| phoneNo.getText().length() != 10) {
phoneNo.setError("Enter valid phone number");
errorCount = errorCount + 1;
if (errorCount == 1) {
phoneNo.requestFocus();
}
} else {
phoneNo.setError(null);
}
if (password.getText().toString().trim().equals("")
|| password.getText().length() != 12) {
password.setError("Enter valid password");
errorCount = errorCount + 1;
if (errorCount == 1) {
password.requestFocus();
}
} else {
password.setError(null);
}
if (errorCount == 0) {
return true;
} else {
return false;
}
}
private void batteryTimer(){
Timer timer = new Timer();
TimerTask hourlyTask = new TimerTask() {
#Override
public void run() {
if (networkUtil.isConnected()) {
batteryLevelCheckService(); // **Getting Error at this Line**
}
else {
offlineBatteryStatus();
}
}
};
timer.scheduleAtFixedRate(hourlyTask, 01, 60000);
}
private void batteryLevelCheckService() {
OkHttpClient client = new OkHttpClient();
String requestURL = String.format(getResources().getString(R.string.service_batteryLevelCheckService));
JSONArray jsonArrayRequest = new JSONArray();
JSONObject jsonRequest;
try {
List<BatteryStatusModel> batStatusOffline = new Select().from(BatteryStatusModel.class).execute();
if (batStatusOffline.size() > 0) {
for (BatteryStatusModel batStatusObject : batStatusOffline) {
jsonRequest = new JSONObject();
jsonRequest.accumulate("strTime", batStatusObject.batStatTime);
jsonRequest.accumulate("batteryStatusLat", "" + batStatusObject.battery_lat);
jsonRequest.accumulate("batteryStatusLog", "" + batStatusObject.battery_lon);
jsonRequest.accumulate("empAuthKey", sharePref.getValueFromSharePref("authKey"));
jsonRequest.accumulate("mobno", "" + sharePref.getValueFromSharePref("mobileno"));
jsonRequest.accumulate("strBatteryStatus", "" + batStatusObject.batteryStatus);
jsonArrayRequest.put(jsonRequest);
}
}
Intent intent = this.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
int percent = (level * 100) / scale;
Date today = Calendar.getInstance().getTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
String time = simpleDateFormat.format(today);
jsonRequest = new JSONObject();
jsonRequest.accumulate("strTime", time);
jsonRequest.accumulate("batteryStatusLat", "" + locationInfo.lastLat);
jsonRequest.accumulate("batteryStatusLon", "" + locationInfo.lastLong);
jsonRequest.accumulate("empAuthKey", sharePref.getValueFromSharePref("authKey"));
jsonRequest.accumulate("mobNo", "" + sharePref.getValueFromSharePref("mobileno"));
jsonRequest.accumulate("strBatteryStatus", "" + percent);
jsonArrayRequest.put(jsonRequest);
} catch (Exception e) {
e.printStackTrace();
}
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonArrayRequest.toString());
Request request = new Request.Builder()
.url(requestURL) // Getting Error at this Line
.post(body).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
String responseString = response.body().string();
try {
JSONObject jsonResponse = new JSONObject(responseString);
String status = jsonResponse.getString("status");
String message = jsonResponse.getString("message");
Log.d("jagteraho", "response :: status: " + status.toString() + " message: " + message);
if (status.equals("success")) {
new Delete().from(BatteryStatusModel.class).execute();
} else if (status.equals("failure")) {
} else if (status.equals("error")) {
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
This is my Logcat
java.lang.IllegalArgumentException: unexpected url: >http://192.168.2.20:8080/jagteraho/batteryStatus/save
at okhttp3.Request$Builder.url(Request.java:143)
at com.aspeage.jagteraho.LoginActivity.batteryLevelCheckService(LoginActivity.java:270)
at com.aspeage.jagteraho.LoginActivity.access$600(LoginActivity.java:59)
at com.aspeage.jagteraho.LoginActivity$4.run(LoginActivity.java:216)
at java.util.Timer$TimerImpl.run(Timer.java:284)
Please help me with the possible solutions i am quite new in Android Development

Your error is coming from OkHttp.
If you search for the error message, you can see where OkHttp is generating it:
https://github.com/square/okhttp/blob/master/okhttp/src/main/java/okhttp3/Request.java#L142
HttpUrl parsed = HttpUrl.parse(url);
if (parsed == null) throw new IllegalArgumentException("unexpected url: " + url);
return url(parsed);
It means that your URL is invalid. As the comment to your question points out: >http://192.168.2.20:8080/jagteraho/batteryStatus/save is not a valid URL.
You need to remove the >.

Related

This is code of image and video of instagram dowloading by link.. after downloading 4 ,5 photos or videos this code not work

This is code of image and video of instagram dowloading by link.. after downloading 4 ,5 photos or videos this code not work .and getting error findata class ..
public class FindData {
private Context context;
private GetDat getData;
String netsubType;
NetworkInfo activeNetworkInfo1;
Boolean s;
public FindData(Context context, GetDat getData) {
this.context = context;
this.getData = getData;
}
public void data(String stringData) {
ArrayList<String> arrayList = new ArrayList<>();
if (stringData.matches("https://www.instagram.com/(.*)")) {
String[] data = stringData.split(Pattern.quote("?"));
String string = data[0];
// if (isNetworklow()) {
//
// Toast.makeText(context, "network low", Toast.LENGTH_SHORT).show();
// }
if (isNetworkAvailable()) {
if (Method.isDownload) {
AsyncHttpClient client = new AsyncHttpClient();
client.get(string + "?__a=1", null, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
String res = new String(responseBody);
try {
JSONObject jsonObject = new JSONObject(res);
String link = null;
JSONObject objectGraphql = jsonObject.getJSONObject("graphql");
JSONObject objectMedia = objectGraphql.getJSONObject("shortcode_media");
boolean isVideo = objectMedia.getBoolean("is_video");
if (isVideo) {
link = objectMedia.getString("video_url");
} else {
link = objectMedia.getString("display_url");
}
arrayList.add(link);
try {
JSONObject objectSidecar = objectMedia.getJSONObject("edge_sidecar_to_children");
JSONArray jsonArray = objectSidecar.getJSONArray("edges");
arrayList.clear();
String edgeSidecar = null;
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
JSONObject node = object.getJSONObject("node");
boolean is_video_group = node.getBoolean("is_video");
if (is_video_group) {
edgeSidecar = node.getString("video_url");
} else {
edgeSidecar = node.getString("display_url");
}
arrayList.add(edgeSidecar);
}
} catch (Exception e) {
Log.e("error_show", e.toString());
}
getData.getData(arrayList, "", true);
Toast.makeText(context, "success", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
Log.e("........POOR NETWORK ........", e.toString());
getData.getData(arrayList, context.getResources().getString(R.string.not_support), false);
Toast.makeText(context, " poor network", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.e("...........on failure +Tag............",error.toString());
Toast.makeText(context, "try again error", Toast.LENGTH_SHORT).show();
getData.getData(arrayList, context.getResources().getString(R.string.wrong), false);
}
});
} else {
getData.getData(arrayList,"ff ", false);
}
} else {
getData.getData(arrayList, context.getResources().getString(R.string.internet_connection), false);
Toast.makeText(context, "no network", Toast.LENGTH_SHORT).show();
}
} else {
getData.getData(arrayList, "invalid link copy again", false);
}
}
//network check
public boolean isNetworkAvailable() {
Log.e("TAG", "=============onFailure===============");
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
assert connectivityManager != null;
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
//netsubType.equals( TelephonyManager.NETWORK_TYPE_EDGE)||netsubType.equals( TelephonyManager.NETWORK_TYPE_1xRTT ));
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
public class DownloadService extends Service {
private int position = 0;
private RemoteViews rv;
private OkHttpClient client;
private final int CHANEL_ID = 105;
private NotificationCompat.Builder builder;
private NotificationManager notificationManager;
private static final String CANCEL_TAG = "c_tag";
private final String NOTIFICATION_CHANNEL_ID = "download_service";
public static final String ACTION_START = "com.download.action.START";
public static final String ACTION_STOP = "com.download.action.STOP";
private final Handler mHandler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(#NotNull Message message) {
int progress = Integer.parseInt(message.obj.toString());
switch (message.what) {
case 1:
rv.setTextViewText(R.id.nf_title, getString(R.string.app_name));
rv.setProgressBar(R.id.progress, 100, progress, false);
rv.setTextViewText(R.id.nf_percentage, getResources().getString(R.string.downloading) + " " + "(" + progress + " %)");
notificationManager.notify(CHANEL_ID, builder.build());
break;
case 2:
if (Constant.downloadArray.size() - 1 != position) {
position++;
init(Constant.downloadArray.get(position));
} else {
// Toast.makeText(getApplicationContext(), getResources().getString(R.string.downloading), Toast.LENGTH_SHORT).show();
position = 0;
stopForeground(false);
stopSelf();
Events.AdapterNotify adapterNotify = new Events.AdapterNotify("");
GlobalBus.getBus().post(adapterNotify);
Method.isDownload = true;
}
break;
}
return false;
}
});
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
builder.setChannelId(NOTIFICATION_CHANNEL_ID);
builder.setSmallIcon(R.drawable.ic_baseline_notes);
builder.setTicker(getResources().getString(R.string.downloading));
builder.setWhen(System.currentTimeMillis());
builder.setOnlyAlertOnce(true);
rv = new RemoteViews(getPackageName(), R.layout.my_custom_notification);
rv.setTextViewText(R.id.nf_title, getString(R.string.app_name));
rv.setProgressBar(R.id.progress, 100, 0, false);
rv.setTextViewText(R.id.nf_percentage, getResources().getString(R.string.downloading) + " " + "(0%)");
Intent intentClose = new Intent(this, DownloadService.class);
intentClose.setAction(ACTION_STOP);
PendingIntent closeIntent = PendingIntent.getService(this, 0, intentClose, 0);
rv.setOnClickPendingIntent(R.id.nf_close, closeIntent);
builder.setCustomContentView(rv);
NotificationChannel mChannel;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getResources().getString(R.string.app_name);// The user-visible name of the channel.
mChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, name, NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(mChannel);
}
startForeground(CHANEL_ID, builder.build());
}
#Override
public void onDestroy() {
super.onDestroy();
stopForeground(false);
stopSelf();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
try {
if (intent.getAction() != null && intent.getAction().equals(ACTION_START)) {
Method.isDownload = false;
init(Constant.downloadArray.get(position));
}
if (intent.getAction() != null && intent.getAction().equals(ACTION_STOP)) {
if (client != null) {
for (Call call : client.dispatcher().runningCalls()) {
if (call.request().tag().equals(CANCEL_TAG))
call.cancel();
}
}
Method.isDownload = true;
stopForeground(false);
stopSelf();
}
} catch (Exception e) {
Log.d("error", e.toString());
stopForeground(false);
stopSelf();
}
return START_STICKY;
}
public void init(final String downloadUrl) {
final String iconsStoragePath = Environment.getExternalStorageDirectory() + getResources().getString(R.string.download_folder_path);
File file = new File(iconsStoragePath);
if (!file.exists()) {
file.mkdir();
}
//Using Date class
Date date = new Date();
//Pattern for showing milliseconds in the time "SSS"
#SuppressLint("SimpleDateFormat")
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
String stringDate = sdf.format(date);
//Using Calendar class
Calendar cal = Calendar.getInstance();
String s = sdf.format(cal.getTime());
final String string;
if (downloadUrl.contains(".jpg")) {
string = "Image-" + s + ".jpg";
} else {
string = "Image-" + s + ".mp4";
}
Log.d("file_name", string);
new Thread(new Runnable() {
#Override
public void run() {
client = new OkHttpClient();
Request.Builder builder = new Request.Builder()
.url(downloadUrl)
.addHeader("Accept-Encoding", "identity")
.get()
.tag(CANCEL_TAG);
Call call = client.newCall(builder.build());
call.enqueue(new Callback() {
#Override
public void onFailure(#NonNull Call call, #NonNull IOException e) {
Log.e("TAG", "=============onFailure222===============");
e.printStackTrace();
Log.d("error_downloading", e.toString());
// Method.isDownload = true;
}
#Override
public void onResponse(#NonNull Call call, #NonNull Response response) throws IOException {
Log.e("TAG", "=============onResponse===============");
Log.e("TAG", "request headers:" + response.request().headers());
Log.e("TAG", "response headers:" + response.headers());
assert response.body() != null;
ResponseBody responseBody = ProgressHelper.withProgress(response.body(), new ProgressUIListener() {
//if you don't need this method, don't override this methd. It isn't an abstract method, just an empty method.
#Override
public void onUIProgressStart(long totalBytes) {
super.onUIProgressStart(totalBytes);
Log.e("TAG", "onUIProgressStart:" + totalBytes);
}
#Override
public void onUIProgressChanged(long numBytes, long totalBytes, float percent, float speed) {
Log.e("TAG", "=============start===============");
Log.e("TAG", "numBytes:" + numBytes);
Log.e("TAG", "totalBytes:" + totalBytes);
Log.e("TAG", "percent:" + percent);
Log.e("TAG", "speed:" + speed);
Log.e("TAG", "============= end ===============");
Message msg = mHandler.obtainMessage();
msg.what = 1;
msg.obj = (int) (100 * percent) + "";
mHandler.sendMessage(msg);
}
//if you don't need this method, don't override this methd. It isn't an abstract method, just an empty method.
#Override
public void onUIProgressFinish() {
super.onUIProgressFinish();
Log.e("TAG", "onUIProgressFinish:");
Message msg = mHandler.obtainMessage();
msg.what = 2;
msg.obj = 0 + "";
mHandler.sendMessage(msg);
if (downloadUrl.contains(".jpg")) {
if (Constant.imageArray != null) {
Constant.imageArray.add(0, new File(iconsStoragePath + "/" + string));
}
} else {
if (Constant.videoArray != null) {
Constant.videoArray.add(0, new File(iconsStoragePath + "/" + string));
}
}
try {
MediaScannerConnection.scanFile(getApplicationContext(), new String[]{iconsStoragePath + "/" + string},
null,
(path, uri) -> {
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
try {
BufferedSource source = responseBody.source();
File outFile = new File(iconsStoragePath + "/" + string);
BufferedSink sink = Okio.buffer(Okio.sink(outFile));
source.readAll(sink);
sink.flush();
source.close();
} catch (Exception e) {
Log.d("show_data", e.toString());
}
}
});
}
}).start();
}
}
**error in FindData class2022-03-11 08:32:20.701 1631-1631/?
E/downloaderinst: Unknown bits set in runtime_flags: 0x8000
2022-03-11 08:59:02.413 1631-1631/com.pinit.downloaderinst3 E/TAG: =============onFailure===============
2022-03-11 08:59:02.539 1631-1631/com.pinit.downloaderinst3 E/DecorView: mWindow.mActivityCurrentConfig is null
2022-03-11 08:59:03.999 1631-1631/com.pinit.downloaderinst3 E/........POOR NETWORK ........: org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
2022-03-11 08:59:04.007 1631-1631/com.pinit.downloaderinst3 E/InputMethodManager: prepareNavigationBarInfo() rootView is null
2022-03-11 08:59:04.123 1631-1631/com.pinit.downloaderinst3 E/ViewRootImpl: sendUserActionEvent() mView returned.

HOW TO ADD TOAST MESSAGE IN onComplete,I am a begginer in Android Studio and I do not much know about java [duplicate]

This question already has answers here:
Can't toast on a thread that has not called Looper.prepare()
(4 answers)
Closed 2 years ago.
I want to show Toast message in my app after finishing the downloading. I took the code on the internet and it works like this:- the app is downloading the video from the server and after that, it adds my own watermark in the video, it works nicely but now I want to show TOAST message after finishing the adding watermark thing. I add a simple Toast code but after finishing the watermark processing app but it automatically closes because of the simple Toast message, so anyone help to fix his coding problem, if you need any additional info than this, then let me know.
THIS IS THE WHOLE CODE OF MY JAVA CLASS
public class DownloadService extends Service {
private DatabaseHandler db;
private NotificationCompat.Builder myNotify;
private String video_id, downloadUrl, file_path_delete, file_path, file_name, layout_type, watermark_image, watermark_on_off;
private RemoteViews rv;
private OkHttpClient client;
private WaterMarkData waterMarkData;
private GPUMp4Composer gpuMp4Composer;
public static final String ACTION_STOP = "com.mydownload.action.STOP";
public static final String ACTION_START = "com.mydownload.action.START";
private String NOTIFICATION_CHANNEL_ID = "download_ch_1";
private static final String CANCEL_TAG = "c_tag";
NotificationManager mNotificationManager;
private boolean isWaterMark = false;
private boolean isResize = false;
private Handler mHandler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message message) {
int progress = Integer.parseInt(message.obj.toString());
switch (message.what) {
case 1:
rv.setTextViewText(R.id.nf_title, getString(R.string.app_name));
rv.setProgressBar(R.id.progress, 100, progress, false);
if (isWaterMark) {
rv.setTextViewText(R.id.nf_percentage, getResources().getString(R.string.watermark) + " " + "(" + progress + " %)");
} else {
rv.setTextViewText(R.id.nf_percentage, getResources().getString(R.string.downloading) + " " + "(" + progress + " %)");
}
myNotify.setCustomContentView(rv);
startForeground(1002, myNotify.build());
break;
case 2:
stopForeground(true);
stopSelf();
break;
}
return false;
}
});
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
db = new DatabaseHandler(getApplicationContext());
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
myNotify = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
myNotify.setChannelId(NOTIFICATION_CHANNEL_ID);
myNotify.setSmallIcon(R.mipmap.ic_launcher);
myNotify.setTicker(getResources().getString(R.string.downloading));
myNotify.setWhen(System.currentTimeMillis());
myNotify.setOnlyAlertOnce(true);
rv = new RemoteViews(getPackageName(),
R.layout.my_custom_notification);
rv.setTextViewText(R.id.nf_title, getString(R.string.app_name));
rv.setProgressBar(R.id.progress, 100, 0, false);
rv.setTextViewText(R.id.nf_percentage, getResources().getString(R.string.downloading) + " " + "(0%)");
Intent closeIntent = new Intent(this, DownloadService.class);
closeIntent.setAction(ACTION_STOP);
PendingIntent pcloseIntent = PendingIntent.getService(this, 0,
closeIntent, 0);
rv.setOnClickPendingIntent(R.id.nf_close, pcloseIntent);
myNotify.setCustomContentView(rv);
NotificationChannel mChannel;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Online Channel download";// The user-visible name of the channel.
mChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, name, NotificationManager.IMPORTANCE_HIGH);
mNotificationManager.createNotificationChannel(mChannel);
}
startForeground(1002, myNotify.build());
}
#Override
public void onDestroy() {
super.onDestroy();
stopForeground(true);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if (intent.getAction() != null && intent.getAction().equals(ACTION_START)) {
video_id = intent.getStringExtra("video_id");
downloadUrl = intent.getStringExtra("downloadUrl");
file_path = intent.getStringExtra("file_path");
file_name = intent.getStringExtra("file_name");
layout_type = intent.getStringExtra("layout_type");
watermark_image = intent.getStringExtra("watermark_image");
watermark_on_off = intent.getStringExtra("watermark_on_off");
assert watermark_on_off != null;
if (watermark_on_off.equals("true")) {
file_path = getExternalCacheDir().getAbsolutePath();
}
file_path_delete = file_path;
init();
}
if (intent.getAction() != null && intent.getAction().equals(ACTION_STOP)) {
stopForeground(true);
stopSelf();
if (gpuMp4Composer != null) {
gpuMp4Composer.cancel();
}
if (waterMarkData != null) {
waterMarkData.cancel(true);
}
if (!db.checkId_video_download(video_id)) {
db.delete_video_download(video_id);
}
File file = new File(file_path_delete, file_name);
if (file.exists()) {
file.delete();
}
Method.isDownload = true;
if (client != null) {
for (Call call : client.dispatcher().runningCalls()) {
if (call.request().tag().equals(CANCEL_TAG))
call.cancel();
}
}
}
return START_STICKY;
}
public void init() {
new Thread(new Runnable() {
#Override
public void run() {
client = new OkHttpClient();
Request.Builder builder = new Request.Builder()
.url(downloadUrl)
.addHeader("Accept-Encoding", "identity")
.get()
.tag(CANCEL_TAG);
Call call = client.newCall(builder.build());
call.enqueue(new Callback() {
#Override
public void onFailure(#NonNull Call call, #NonNull IOException e) {
Log.e("TAG", "=============onFailure===============");
e.printStackTrace();
Log.d("error_downloading", e.toString());
Method.isDownload = true;
}
#Override
public void onResponse(#NonNull Call call, #NonNull Response response) throws IOException {
Log.e("TAG", "=============onResponse===============");
Log.e("TAG", "request headers:" + response.request().headers());
Log.e("TAG", "response headers:" + response.headers());
assert response.body() != null;
final ResponseBody responseBody = ProgressHelper.withProgress(response.body(), new ProgressUIListener() {
//if you don't need this method, don't override this methd. It isn't an abstract method, just an empty method.
#Override
public void onUIProgressStart(long totalBytes) {
super.onUIProgressStart(totalBytes);
Log.e("TAG", "onUIProgressStart:" + totalBytes);
Toast.makeText(getApplicationContext(), getResources().getString(R.string.downloading), Toast.LENGTH_SHORT).show();
}
#Override
public void onUIProgressChanged(long numBytes, long totalBytes, float percent, float speed) {
Log.e("TAG", "=============start===============");
Log.e("TAG", "numBytes:" + numBytes);
Log.e("TAG", "totalBytes:" + totalBytes);
Log.e("TAG", "percent:" + percent);
Log.e("TAG", "speed:" + speed);
Log.e("TAG", "============= end ===============");
Message msg = mHandler.obtainMessage();
msg.what = 1;
msg.obj = (int) (100 * percent) + "";
mHandler.sendMessage(msg);
}
//if you don't need this method, don't override this method. It isn't an abstract method, just an empty method.
#Override
public void onUIProgressFinish() {
super.onUIProgressFinish();
Log.e("TAG", "onUIProgressFinish:");
if (watermark_on_off.equals("true")) {
//call data watermark class add to watermark
waterMarkData = new WaterMarkData();
waterMarkData.execute();
} else {
Message msg = mHandler.obtainMessage();
msg.what = 2;
msg.obj = 0 + "";
mHandler.sendMessage(msg);
Method.isDownload = true;
showMedia(file_path, file_name);
}
}
});
try {
BufferedSource source = responseBody.source();
File outFile = new File(file_path + "/" + file_name);
BufferedSink sink = Okio.buffer(Okio.sink(outFile));
source.readAll(sink);
sink.flush();
source.close();
} catch (Exception e) {
Log.d("show_data", e.toString());
}
}
});
}
}).start();
}
#SuppressLint("StaticFieldLeak")
class WaterMarkData extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... strings) {
//check water mark on or off
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(downloadUrl);
mp.prepareAsync();
mp.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
#Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
Log.d("call_data", "sizedata");
if (layout_type.equals("Portrait")) {
if (height <= 700) {
isResize = true;
}
} else {
if (height <= 400 || width <= 400) {
isResize = true;
}
}
watermark();//call method water mark adding
}
});
} catch (IllegalArgumentException e) {
e.printStackTrace();
watermark();//call method water mark adding
Log.d("call_data", "error");
} catch (SecurityException e) {
e.printStackTrace();
watermark();//call method water mark adding
Log.d("call_data", "error");
} catch (IllegalStateException e) {
e.printStackTrace();
watermark();//call method water mark adding
Log.d("call_data", "error");
} catch (IOException e) {
e.printStackTrace();
watermark();//call method water mark adding
Log.d("call_data", "error");
} catch (Exception e) {
e.printStackTrace();
watermark();//call method water mark adding
Log.d("call_data", "error");
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d("data", "execute");
}
}
private void watermark() {
//check water mark on or off
new Thread(new Runnable() {
#Override
public void run() {
Bitmap image = null;
try {
URL url = new URL(watermark_image);
try {
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (Exception e) {
Log.d("error_data", e.toString());
}
} catch (IOException e) {
Log.d("error", e.toString());
System.out.println(e);
image = BitmapFactory.decodeResource(getResources(), R.drawable.watermark);
}
if (isResize) {
image = getResizedBitmap(image, 40, 40);
isResize = false;
}
String destinationPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Latest_Video_Status/";
file_path_delete = destinationPath;
gpuMp4Composer = new GPUMp4Composer(file_path + "/" + file_name, destinationPath + file_name)
.filter(new GlWatermarkFilter(image, GlWatermarkFilter.Position.RIGHT_BOTTOM))
.listener(new GPUMp4Composer.Listener() {
#Override
public void onProgress(double progress) {
isWaterMark = true;
double value = progress * 100;
int i = (int) value;
Message msg = mHandler.obtainMessage();
msg.what = 1;
msg.obj = i + "";
mHandler.sendMessage(msg);
Log.d(TAG, "onProgress = " + progress);
Log.d("call_data", "watermark");
}
#Override
public void onCompleted() {
isWaterMark = false;
new File(getExternalCacheDir().getAbsolutePath() + "/" + file_name).delete();//delete file to save in cash folder
Message msg = mHandler.obtainMessage();
msg.what = 2;
msg.obj = 0 + "";
mHandler.sendMessage(msg);
Method.isDownload = true;
showMedia(destinationPath, file_name);
Log.d(TAG, "onCompleted()");
runOnUiThread(new Runnable()
{
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Your text.",
Toast.LENGTH_SHORT).show();
}
}
);
}
#Override
public void onCanceled() {
isWaterMark = false;
Message msg = mHandler.obtainMessage();
msg.what = 2;
msg.obj = 0 + "";
mHandler.sendMessage(msg);
Method.isDownload = true;
Log.d(TAG, "onCanceled");
}
#Override
public void onFailed(Exception exception) {
isWaterMark = false;
Message msg = mHandler.obtainMessage();
msg.what = 2;
msg.obj = 0 + "";
mHandler.sendMessage(msg);
Method.isDownload = true;
Log.e(TAG, "onFailed()", exception);
}
})
.start();
}
}).start();
}
public Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// CREATE A MATRIX FOR THE MANIPULATION
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// "RECREATE" THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(
bm, 0, 0, width, height, matrix, false);
bm.recycle();
return resizedBitmap;
}
public void showMedia(String file_path, String file_name) {
try {
MediaScannerConnection.scanFile(getApplicationContext(), new String[]{file_path + "/" + file_name},
null,
new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
ERROR
Can't toast on a thread that has not called Looper.prepare()
How what to do now to fix this issue, please anyone help me.
Solution
new Handler(Looper.getMainLooper()).post(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "KISHAN",
Toast.LENGTH_SHORT).show();
}
});
Add the following line in onCompleted():-
Toast toast = Toast.makeText(getApplicationContext(),
"The text you want to show",
Toast.LENGTH_SHORT
);
If that doesn't work, then let me know.
Edit :-
Working code:-
private DatabaseHandler db;
private NotificationCompat.Builder myNotify;
private String video_id, downloadUrl, file_path_delete, file_path, file_name, layout_type, watermark_image, watermark_on_off;
private RemoteViews rv;
private OkHttpClient client;
private WaterMarkData waterMarkData;
private GPUMp4Composer gpuMp4Composer;
public static final String ACTION_STOP = "com.mydownload.action.STOP";
public static final String ACTION_START = "com.mydownload.action.START";
private String NOTIFICATION_CHANNEL_ID = "download_ch_1";
private static final String CANCEL_TAG = "c_tag";
NotificationManager mNotificationManager;
private boolean isWaterMark = false;
private boolean isResize = false;
public class ServiceHandler {
private final Activity mactivity;
public ServiceHandler(Activity activity)
{
mActivity = activity;
}
public void run() {
<Your Activity Name>.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast toast = Toast.makeText(getApplicationContext(), "Your text", Toast.LENGTH_SHORT).show();
}
});
}
}
private Handler mHandler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message message) {
int progress = Integer.parseInt(message.obj.toString());
switch (message.what) {
case 1:
rv.setTextViewText(R.id.nf_title, getString(R.string.app_name));
rv.setProgressBar(R.id.progress, 100, progress, false);
if (isWaterMark) {
rv.setTextViewText(R.id.nf_percentage, getResources().getString(R.string.watermark) + " " + "(" + progress + " %)");
} else {
rv.setTextViewText(R.id.nf_percentage, getResources().getString(R.string.downloading) + " " + "(" + progress + " %)");
}
myNotify.setCustomContentView(rv);
startForeground(1002, myNotify.build());
break;
case 2:
stopForeground(true);
stopSelf();
break;
}
return false;
}
});
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
db = new DatabaseHandler(getApplicationContext());
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
myNotify = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
myNotify.setChannelId(NOTIFICATION_CHANNEL_ID);
myNotify.setSmallIcon(R.mipmap.ic_launcher);
myNotify.setTicker(getResources().getString(R.string.downloading));
myNotify.setWhen(System.currentTimeMillis());
myNotify.setOnlyAlertOnce(true);
rv = new RemoteViews(getPackageName(),
R.layout.my_custom_notification);
rv.setTextViewText(R.id.nf_title, getString(R.string.app_name));
rv.setProgressBar(R.id.progress, 100, 0, false);
rv.setTextViewText(R.id.nf_percentage, getResources().getString(R.string.downloading) + " " + "(0%)");
Intent closeIntent = new Intent(this, DownloadService.class);
closeIntent.setAction(ACTION_STOP);
PendingIntent pcloseIntent = PendingIntent.getService(this, 0,
closeIntent, 0);
rv.setOnClickPendingIntent(R.id.nf_close, pcloseIntent);
myNotify.setCustomContentView(rv);
NotificationChannel mChannel;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Online Channel download";// The user-visible name of the channel.
mChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, name, NotificationManager.IMPORTANCE_HIGH);
mNotificationManager.createNotificationChannel(mChannel);
}
startForeground(1002, myNotify.build());
}
#Override
public void onDestroy() {
super.onDestroy();
stopForeground(true);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if (intent.getAction() != null && intent.getAction().equals(ACTION_START)) {
video_id = intent.getStringExtra("video_id");
downloadUrl = intent.getStringExtra("downloadUrl");
file_path = intent.getStringExtra("file_path");
file_name = intent.getStringExtra("file_name");
layout_type = intent.getStringExtra("layout_type");
watermark_image = intent.getStringExtra("watermark_image");
watermark_on_off = intent.getStringExtra("watermark_on_off");
assert watermark_on_off != null;
if (watermark_on_off.equals("true")) {
file_path = getExternalCacheDir().getAbsolutePath();
}
file_path_delete = file_path;
init();
}
if (intent.getAction() != null && intent.getAction().equals(ACTION_STOP)) {
stopForeground(true);
stopSelf();
if (gpuMp4Composer != null) {
gpuMp4Composer.cancel();
}
if (waterMarkData != null) {
waterMarkData.cancel(true);
}
if (!db.checkId_video_download(video_id)) {
db.delete_video_download(video_id);
}
File file = new File(file_path_delete, file_name);
if (file.exists()) {
file.delete();
}
Method.isDownload = true;
if (client != null) {
for (Call call : client.dispatcher().runningCalls()) {
if (call.request().tag().equals(CANCEL_TAG))
call.cancel();
}
}
}
return START_STICKY;
}
public void init() {
new Thread(new Runnable() {
#Override
public void run() {
client = new OkHttpClient();
Request.Builder builder = new Request.Builder()
.url(downloadUrl)
.addHeader("Accept-Encoding", "identity")
.get()
.tag(CANCEL_TAG);
Call call = client.newCall(builder.build());
call.enqueue(new Callback() {
#Override
public void onFailure(#NonNull Call call, #NonNull IOException e) {
Log.e("TAG", "=============onFailure===============");
e.printStackTrace();
Log.d("error_downloading", e.toString());
Method.isDownload = true;
}
#Override
public void onResponse(#NonNull Call call, #NonNull Response response) throws IOException {
Log.e("TAG", "=============onResponse===============");
Log.e("TAG", "request headers:" + response.request().headers());
Log.e("TAG", "response headers:" + response.headers());
assert response.body() != null;
final ResponseBody responseBody = ProgressHelper.withProgress(response.body(), new ProgressUIListener() {
//if you don't need this method, don't override this methd. It isn't an abstract method, just an empty method.
#Override
public void onUIProgressStart(long totalBytes) {
super.onUIProgressStart(totalBytes);
Log.e("TAG", "onUIProgressStart:" + totalBytes);
Toast.makeText(getApplicationContext(), getResources().getString(R.string.downloading), Toast.LENGTH_SHORT).show();
}
#Override
public void onUIProgressChanged(long numBytes, long totalBytes, float percent, float speed) {
Log.e("TAG", "=============start===============");
Log.e("TAG", "numBytes:" + numBytes);
Log.e("TAG", "totalBytes:" + totalBytes);
Log.e("TAG", "percent:" + percent);
Log.e("TAG", "speed:" + speed);
Log.e("TAG", "============= end ===============");
Message msg = mHandler.obtainMessage();
msg.what = 1;
msg.obj = (int) (100 * percent) + "";
mHandler.sendMessage(msg);
}
//if you don't need this method, don't override this method. It isn't an abstract method, just an empty method.
#Override
public void onUIProgressFinish() {
super.onUIProgressFinish();
Log.e("TAG", "onUIProgressFinish:");
if (watermark_on_off.equals("true")) {
//call data watermark class add to watermark
waterMarkData = new WaterMarkData();
waterMarkData.execute();
} else {
Message msg = mHandler.obtainMessage();
msg.what = 2;
msg.obj = 0 + "";
mHandler.sendMessage(msg);
Method.isDownload = true;
showMedia(file_path, file_name);
}
}
});
try {
BufferedSource source = responseBody.source();
File outFile = new File(file_path + "/" + file_name);
BufferedSink sink = Okio.buffer(Okio.sink(outFile));
source.readAll(sink);
sink.flush();
source.close();
} catch (Exception e) {
Log.d("show_data", e.toString());
}
}
});
}
}).start();
}
#SuppressLint("StaticFieldLeak")
class WaterMarkData extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... strings) {
//check water mark on or off
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(downloadUrl);
mp.prepareAsync();
mp.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
#Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
Log.d("call_data", "sizedata");
if (layout_type.equals("Portrait")) {
if (height <= 700) {
isResize = true;
}
} else {
if (height <= 400 || width <= 400) {
isResize = true;
}
}
watermark();//call method water mark adding
}
});
} catch (IllegalArgumentException e) {
e.printStackTrace();
watermark();//call method water mark adding
Log.d("call_data", "error");
} catch (SecurityException e) {
e.printStackTrace();
watermark();//call method water mark adding
Log.d("call_data", "error");
} catch (IllegalStateException e) {
e.printStackTrace();
watermark();//call method water mark adding
Log.d("call_data", "error");
} catch (IOException e) {
e.printStackTrace();
watermark();//call method water mark adding
Log.d("call_data", "error");
} catch (Exception e) {
e.printStackTrace();
watermark();//call method water mark adding
Log.d("call_data", "error");
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d("data", "execute");
}
}
private void watermark() {
//check water mark on or off
new Thread(new Runnable() {
#Override
public void run() {
Bitmap image = null;
try {
URL url = new URL(watermark_image);
try {
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (Exception e) {
Log.d("error_data", e.toString());
}
} catch (IOException e) {
Log.d("error", e.toString());
System.out.println(e);
image = BitmapFactory.decodeResource(getResources(), R.drawable.watermark);
}
if (isResize) {
image = getResizedBitmap(image, 40, 40);
isResize = false;
}
String destinationPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Latest_Video_Status/";
file_path_delete = destinationPath;
gpuMp4Composer = new GPUMp4Composer(file_path + "/" + file_name, destinationPath + file_name)
.filter(new GlWatermarkFilter(image, GlWatermarkFilter.Position.RIGHT_BOTTOM))
.listener(new GPUMp4Composer.Listener() {
#Override
public void onProgress(double progress) {
isWaterMark = true;
double value = progress * 100;
int i = (int) value;
Message msg = mHandler.obtainMessage();
msg.what = 1;
msg.obj = i + "";
mHandler.sendMessage(msg);
Log.d(TAG, "onProgress = " + progress);
Log.d("call_data", "watermark");
}
#Override
public void onCompleted() {
isWaterMark = false;
new File(getExternalCacheDir().getAbsolutePath() + "/" + file_name).delete();//delete file to save in cash folder
Message msg = mHandler.obtainMessage();
msg.what = 2;
msg.obj = 0 + "";
mHandler.sendMessage(msg);
Method.isDownload = true;
showMedia(destinationPath, file_name);
Log.d(TAG, "onCompleted()");
ServiceHandler sh = new ServiceHandler(this);
sh.run();
}
#Override
public void onCanceled() {
isWaterMark = false;
Message msg = mHandler.obtainMessage();
msg.what = 2;
msg.obj = 0 + "";
mHandler.sendMessage(msg);
Method.isDownload = true;
Log.d(TAG, "onCanceled");
}
#Override
public void onFailed(Exception exception) {
isWaterMark = false;
Message msg = mHandler.obtainMessage();
msg.what = 2;
msg.obj = 0 + "";
mHandler.sendMessage(msg);
Method.isDownload = true;
Log.e(TAG, "onFailed()", exception);
}
})
.start();
}
}).start();
}
public Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// CREATE A MATRIX FOR THE MANIPULATION
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// "RECREATE" THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(
bm, 0, 0, width, height, matrix, false);
bm.recycle();
return resizedBitmap;
}
public void showMedia(String file_path, String file_name) {
try {
MediaScannerConnection.scanFile(getApplicationContext(), new String[]{file_path + "/" + file_name},
null,
new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
}

android - java - parse DB : Logics for a meeting request

I'm creating an android app using parse database .
In this app I have created a meeting invite function for the users .
one user can invite another user. and a push notification system also
there for the invite function if someone invites other person a push
notification goes to that person ..
meeting invite and push notification are working fine,
The problem is
when logged in user is A he won't be able to request himself to a meeting . it means if user A is logged in user, he should be excluded from meeting invites .
But I'm unable to add that logic here ,
if anyone can please help me in this ??
java class
public class SingleIndividualInvite extends AppCompatActivity {
String objectId;
protected Button btYes, btNo;
protected TextView txtv;
protected TextView txtv1;
protected ImageView txtv2;
protected ImageView txtv3;
protected TextView individualOrganization;
Button emailPerson;
Button callPerson;
Button callPersonTelephone;
String personEmail, personNumber, personNumberTelephone;
LinearLayout messageLayout, buttonLayout;
ParseObject thisPerson, thisEvent;
TextView inviteMessage;
String currentUserName;
String receiverUserName;
String currentMeeting;
ParseUser parseUser = ParseUser.getCurrentUser();
boolean myInvite;
String eventName, eventID, senderName, senderID, receiverName, receiverID, meetingStatus;
String[] month = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
Calendar itemCalendar = Calendar.getInstance();
Calendar currentCalendar = Calendar.getInstance();
boolean noRequest = true, canRequest = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Window window = getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
// finally change the color
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.setStatusBarColor(Color.parseColor("#083266"));
}
setContentView(R.layout.activity_single_individual_event);
txtv =(TextView)findViewById(R.id.txt123);
txtv1 =(TextView)findViewById(R.id.coporateSector);
txtv2 =(ImageView)findViewById(R.id.txt12345);
txtv3 =(ImageView)findViewById(R.id.txt123456);
individualOrganization =(TextView) findViewById(R.id.individualOrganization);
btYes = (Button) findViewById(R.id.button6);
btNo = (Button) findViewById(R.id.button7);
messageLayout = (LinearLayout) findViewById(R.id.statusLayout);
buttonLayout = (LinearLayout) findViewById(R.id.buttonLayout);
inviteMessage = (TextView) findViewById(R.id.inviteMessage);
Intent i =getIntent();
objectId = i.getStringExtra("objectId");
eventID = i.getStringExtra("eventId");
eventName = i.getStringExtra("eventName");
ParseQuery<ParseObject> query = ParseQuery.getQuery("_User");
query.setLimit(2000);
query.getInBackground(objectId, new GetCallback<ParseObject>() {
public void done(final ParseObject object, ParseException e) {
if (e == null) {
thisPerson = object;
String username = object.getString("firstname");
txtv.setText(username + " " + object.getString("lastname"));
String position = object.getString("position");
txtv1.setText(position);
String organizationName = object.getString("organizationName");
individualOrganization.setText(organizationName);
URL url = null;
try {
url = new URL("" + object.getString("image"));
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
Glide.with(getApplicationContext())
.load(String.valueOf(url))
.into(txtv2);
try {
url = new URL("" + object.getString("image"));
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
Glide.with(getApplicationContext())
.load(String.valueOf(url))
.centerCrop()
.into(txtv3);
try {
ParseRelation<ParseUser> relation = object.getRelation("attenders");
ParseQuery<ParseUser> query = relation.getQuery();
query.whereEqualTo("objectId", ParseUser.getCurrentUser().getObjectId());
ParseUser user = query.getFirst();
// setButton(true);
// updateList();
} catch (ParseException pe) {
// setButton(false);
}
try{
JSONObject jsonObject = parseObjectToJson(object);
Log.d("Object", jsonObject.toString());
Log.d("Email", "+" + object.get("email"));
personNumber = jsonObject.getString("telephone");
personEmail = jsonObject.getString("email");
}catch (Exception je){
}
currentUserName = parseUser.getString("firstname") + " " + parseUser.getString("lastname");
receiverUserName = thisPerson.getString("firstname") + " " + thisPerson.getString("lastname");
ParseQuery<ParseObject> eventQuery = ParseQuery.getQuery("Event");
eventQuery.getInBackground(eventID, new GetCallback<ParseObject>() {
#Override
public void done(ParseObject object, ParseException e) {
if(e == null){
thisEvent = object;
currentCalendar.set(Calendar.HOUR, 0);
currentCalendar.set(Calendar.MINUTE, 0);
currentCalendar.getTime();
String[] itemCalendarDetails = thisEvent.getString("date").split(" ");
int itemMonth = 0;
for(int j=0; j<month.length; j++){
if(itemCalendarDetails[1].equals(month[j])){
itemMonth = j;
break;
}
}
itemCalendar.set(Integer.parseInt(itemCalendarDetails[3]), itemMonth,
Integer.parseInt(itemCalendarDetails[2].substring(0, itemCalendarDetails[2].length()-2)));
if(itemCalendar.after(currentCalendar)) {
canRequest = true;
fetchMeeting();
}else{
canRequest = false;
setLayout();
}
}else{
}
}
});
} else {
}
individualOrganization.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String organizationID = thisPerson.getString("organizationID");
if(organizationID == null || organizationID.equals("")){
Toast.makeText(SingleIndividualInvite.this, "Sorry No Organization Available!", Toast.LENGTH_SHORT).show();
}else{
Intent i = new Intent(getApplicationContext(), SingleCorporate.class);
i.putExtra("objectId", organizationID);
i.putExtra("image", organizationID);
startActivity(i);
}
}
});
}
});
btYes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setButton(true);
ParseUser parseUser = ParseUser.getCurrentUser();
if(noRequest){
noRequest = false;
myInvite = true;
meetingStatus = "NA";
sendCustomPush(thisPerson.getString("push_id"), true);
try{
ParseObject meetingObject = new ParseObject("Meeting");
meetingObject.put("senderName", currentUserName);
meetingObject.put("recieverName", receiverUserName);
meetingObject.put("eventName", eventName);
meetingObject.put("accepted", false);
meetingObject.put("sender", ParseObject.createWithoutData("_User", parseUser.getObjectId()));
meetingObject.put("reciever", ParseObject.createWithoutData("_User", thisPerson.getObjectId()));
meetingObject.put("event", ParseObject.createWithoutData("Event", eventID));
meetingObject.save();
}catch (ParseException pe){
pe.printStackTrace();
Toast.makeText(getApplicationContext(), "Cannot invite right now!", Toast.LENGTH_SHORT).show();
}
}else{
myInvite = false;
noRequest = false;
meetingStatus = "ACCEPTED";
sendCustomPush(thisPerson.getString("push_id"), false);
ParseQuery<ParseObject> invitedMe = ParseQuery.getQuery("Meeting");
invitedMe.include("reciever");
invitedMe.include("sender");
invitedMe.include("event");
invitedMe.whereEqualTo("sender", ParseObject.createWithoutData("_User", thisPerson.getObjectId()));
invitedMe.whereEqualTo("reciever", ParseObject.createWithoutData("_User", parseUser.getObjectId()));
invitedMe.whereEqualTo("event", ParseObject.createWithoutData("Event", eventID));
invitedMe.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if(e == null){
objects.get(0).put("accepted", true);
objects.get(0).saveInBackground();
}else {
}
}
});
}
}
});
btNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ParseUser parseUser = ParseUser.getCurrentUser();
setButton(false);
if(noRequest){
Toast.makeText(SingleIndividualInvite.this, "Kindly Request for a meeting First!", Toast.LENGTH_SHORT).show();
}else {
if(myInvite){
myInvite = true;
noRequest = false;
meetingStatus = "NA";
ParseQuery<ParseObject> invitedThem = ParseQuery.getQuery("Meeting");
invitedThem.whereEqualTo("objectId", currentMeeting);
invitedThem.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if(e==null) {
for (ParseObject delete : objects) {
try{
delete.delete();
Toast.makeText(getApplicationContext(), "Invite Cancelled", Toast.LENGTH_SHORT).show();
}catch (ParseException pe){
pe.printStackTrace();
Toast.makeText(getApplicationContext(), "Cannot retrieve Meeting!", Toast.LENGTH_SHORT).show();
}
}
}else{
Toast.makeText(getApplicationContext(), "Cannot retrieve Meeting!", Toast.LENGTH_SHORT).show();
}
}
});
}else {
myInvite = false;
noRequest = false;
meetingStatus = "NA";
ParseQuery<ParseObject> invitedMe = ParseQuery.getQuery("Meeting");
invitedMe.include("reciever");
invitedMe.include("sender");
invitedMe.include("event");
invitedMe.whereEqualTo("sender", ParseObject.createWithoutData("_User", thisPerson.getObjectId()));
invitedMe.whereEqualTo("reciever", ParseObject.createWithoutData("_User", parseUser.getObjectId()));
invitedMe.whereEqualTo("event", ParseObject.createWithoutData("Event", eventID));
invitedMe.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if(e == null){
objects.get(0).put("accepted", true);
objects.get(0).saveInBackground();
}else {
}
}
});
}
}
setLayout();
}
});
}
public void setButton(boolean status){
if(status){
btYes.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
btYes.setTextColor(Color.WHITE);
btYes.setClickable(false);
btNo.setBackgroundColor(Color.WHITE);
btNo.setTextColor(getResources().getColor(R.color.colorPrimary));
btNo.setClickable(true);
}else{
btYes.setBackgroundColor(Color.WHITE);
btYes.setTextColor(getResources().getColor(R.color.colorPrimary));
btYes.setClickable(true);
btNo.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
btNo.setTextColor(Color.WHITE);
btNo.setClickable(false);
}
}
private JSONObject parseObjectToJson(ParseObject parseObject) throws ParseException, JSONException {
JSONObject jsonObject = new JSONObject();
parseObject.fetchIfNeeded();
Set<String> keys = parseObject.keySet();
for (String key : keys) {
Object objectValue = parseObject.get(key);
if (objectValue instanceof ParseObject) {
jsonObject.put(key, parseObjectToJson(parseObject.getParseObject(key)));
} else if (objectValue instanceof ParseRelation) {
} else {
jsonObject.put(key, objectValue.toString());
}
}
return jsonObject;
}
public void sendCustomPush(String receiverPushID, boolean isRequesting){
String payBody;
if(receiverPushID.equals("") || receiverPushID == null){
Toast.makeText(getApplicationContext(), "Invite Sent. User is not registered for push!", Toast.LENGTH_SHORT).show();
}else{
if(isRequesting){
payBody = "{\r\n " +
"\"app_id\": \"APP_ID HERE \",\r\n " +
"\"include_player_ids\": [\"" + receiverPushID + "\"]," + "\r\n " +
"\"data\": {\"eventName\": \"" + eventName +"\", \"eventId\":\""+ eventID + "\", \"personId\":\"" + thisPerson.getObjectId() + "\"},\r\n " +
"\"contents\": {\"en\": \"" + currentUserName + " has requested for a meeting with you.\"},\r\n " +
"\"headings\": {\"en\": \"Meeting Alert!\"}" +
"\r\n}";
}else{
payBody = "{\r\n " +
"\"app_id\": \" APP_ID HERE \",\r\n " +
"\"include_player_ids\": [\"" + receiverPushID + "\"]," + "\r\n " +
"\"data\": {\"eventName\": \"" + eventName +"\", \"eventId\":\""+ eventID + "\", \"personId\":\"" + thisPerson.getObjectId() + "\"},\r\n " +
"\"contents\": {\"en\": \"" + currentUserName + " has accepted your meeting request.\"},\r\n " +
"\"headings\": {\"en\": \"Meeting Alert!\"}" +
"\r\n}";
}
OutputStreamWriter pushPayLoadWriter = null;
Scanner pushPayLoadReader = null;
HttpURLConnection pushRequest = null;
try{
URL postURL = new URL(" ");
pushRequest = (HttpURLConnection) postURL.openConnection();
pushRequest.setRequestMethod("POST");
pushRequest.setUseCaches(false);
pushRequest.setRequestProperty("Accept", "application/json");
pushRequest.setRequestProperty("Content-Type", "application/json");
pushRequest.setRequestProperty("X-Parse-Client-Key", "");
pushRequest.connect();
pushPayLoadWriter = new OutputStreamWriter(pushRequest.getOutputStream());
pushPayLoadWriter.write(payBody);
pushPayLoadWriter.flush();
pushPayLoadReader = new Scanner(pushRequest.getInputStream());
String responseLoad = "";
while(pushPayLoadReader.hasNext()){
responseLoad += pushPayLoadReader.next();
}
Log.d("Push Request Response", responseLoad);
}catch (Exception ue){
ue.printStackTrace();
}finally {
pushRequest.disconnect();
}
}
}
public void fetchMeeting(){
//Handling Meeting Invite
ParseQuery<ParseObject> invitedThem = ParseQuery.getQuery("Meeting");
invitedThem.include("reciever");
invitedThem.include("sender");
invitedThem.include("event");
invitedThem.whereEqualTo("event", ParseObject.createWithoutData("Event", eventID));
invitedThem.whereEqualTo("sender", ParseObject.createWithoutData("_User", parseUser.getObjectId()));
invitedThem.whereEqualTo("reciever", ParseObject.createWithoutData("_User", thisPerson.getObjectId()));
invitedThem.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if(e == null){
if(objects.size() == 0){
myInvite = false;
Log.d("No Request", "No Request");
ParseQuery<ParseObject> invitedMe = ParseQuery.getQuery("Meeting");
invitedMe.include("reciever");
invitedMe.include("sender");
invitedMe.include("event");
invitedMe.whereEqualTo("event", ParseObject.createWithoutData("Event", eventID));
invitedMe.whereEqualTo("sender", ParseObject.createWithoutData("_User", thisPerson.getObjectId()));
invitedMe.whereEqualTo("reciever", ParseObject.createWithoutData("_User", parseUser.getObjectId()));
invitedMe.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if(e == null){
if(objects.size() == 0){
noRequest = true;
setLayout();
}else{
if(objects.get(0).getBoolean("accepted")){
meetingStatus = "ACCEPTED";
}else{
meetingStatus = "NA";
}
noRequest = false;
setLayout();
}
}else{
Toast.makeText(SingleIndividualInvite.this, "Unable to fetch Meeting. Please Try Again!", Toast.LENGTH_SHORT).show();
}
}
});
}else{
if(objects.get(0).getBoolean("accepted")){
meetingStatus = "ACCEPTED";
}else{
meetingStatus = "NA";
}
noRequest = false;
myInvite = true;
setLayout();
}
}else{
Toast.makeText(SingleIndividualInvite.this, "Unable to fetch Meeting. Please Try Again!", Toast.LENGTH_SHORT).show();
}
}
});
}
public void setLayout(){
if(canRequest){
if(noRequest){
setButton(false);
buttonLayout.setVisibility(View.VISIBLE);
inviteMessage.setVisibility(View.VISIBLE);
messageLayout.setVisibility(View.VISIBLE);
inviteMessage.setText("Do you want to invite this person for a meeting?");
}else{
if(myInvite){
setButton(true);
inviteMessage.setVisibility(View.VISIBLE);
messageLayout.setVisibility(View.VISIBLE);
if(meetingStatus.equals("ACCEPTED")){
buttonLayout.setVisibility(View.INVISIBLE);
inviteMessage.setText("You request has been accepted, be ready fo the meeting.");
}else{
buttonLayout.setVisibility(View.VISIBLE);
inviteMessage.setText("You have already requested a meeting with this attendee and it's waiting for approval.");
}
}else{
inviteMessage.setVisibility(View.VISIBLE);
messageLayout.setVisibility(View.VISIBLE);
buttonLayout.setVisibility(View.VISIBLE);
if(meetingStatus.equals("ACCEPTED")){
setButton(true);
inviteMessage.setText("You have already accepted the meeting request. Press NO to cancel it!");
}else{
setButton(false);
inviteMessage.setText("You have been requested for a meeting. Do you wish to accept it?");
}
}
}
}else{
buttonLayout.setVisibility(View.INVISIBLE);
inviteMessage.setVisibility(View.VISIBLE);
messageLayout.setVisibility(View.VISIBLE);
inviteMessage.setText("Sorry, you cannot respond to this event. This event has already passed.");
}
}
}
hi, I guys I found answer
if(ParseUser.getCurrentUser().getObjectId().equals(objectId)){
btYes.setVisibility(View.INVISIBLE);
btNo.setVisibility(View.INVISIBLE);
}

Can't use the SASLXFacebookPlatformMechanism class in making android xmpp facebook chat client

I m trying to make a simple version facebook messenger.The code that i used has worked well for gtalk and requires facebook authentication to be used for chatting with facebook friends.For that, i have used SASLXFacebookPlatfromMechanism class where i will store the api token and api key along with the apisecret of my app. The problem is SASLXFacebookPlatfromMechanism.java class is full of errors which i cannot resolve at all.Here are my classes-
**MainActivity.java**
public class MainActivity extends ActionBarActivity {
private ArrayList<String> messages = new ArrayList();
private Handler mHandler = new Handler();
private SettingsDialog mDialog;
private EditText mRecipient;
private EditText mSendText;
private ListView mList;
private XMPPConnection connection;
/**
* Called with the activity is first created.
*/
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Log.i("XMPPClient", "onCreate called");
setContentView(R.layout.activity_main);
mRecipient = (EditText) this.findViewById(R.id.recipient);
Log.i("XMPPClient", "mRecipient = " + mRecipient);
mSendText = (EditText) this.findViewById(R.id.sendText);
Log.i("XMPPClient", "mSendText = " + mSendText);
mList = (ListView) this.findViewById(R.id.listMessages);
Log.i("XMPPClient", "mList = " + mList);
setListAdapter();
// Dialog for getting the xmpp settings
mDialog = new SettingsDialog(this);
// Set a listener to show the settings dialog
Button setup = (Button) this.findViewById(R.id.setup);
setup.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mHandler.post(new Runnable() {
public void run() {
mDialog.show();
}
});
}
});
// Set a listener to send a chat text message
Button send = (Button) this.findViewById(R.id.send);
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
try
{
String to = mRecipient.getText().toString();
String text = mSendText.getText().toString();
Log.i("XMPPClient", "Sending text [" + text + "] to [" + to + "]");
Message msg = new Message(to, Message.Type.chat);
msg.setBody(text);
connection.sendPacket(msg);
messages.add(connection.getUser() + ":");
messages.add(text);
setListAdapter();
}catch(Exception e)
{
Toast.makeText(MainActivity.this, "Error="+e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
/**
* Called by Settings dialog when a connection is establised with the XMPP server
*
* #param connection
*/
public void setConnection (XMPPConnection connection) {
this.connection = connection;
if (connection != null) {
// Add a packet listener to get messages sent to us
PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
connection.addPacketListener(new PacketListener() {
public void processPacket(Packet packet) {
Message message = (Message) packet;
if (message.getBody() != null) {
String fromName = StringUtils.parseBareAddress(message.getFrom());
Log.i("XMPPClient", "Got text [" + message.getBody() + "] from [" + fromName + "]");
messages.add(fromName + ":");
messages.add(message.getBody());
// Add the incoming message to the list view
mHandler.post(new Runnable() {
public void run() {
setListAdapter();
}
});
}
}
}, filter);
}
}
private void setListAdapter
() {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.multi_line_list_item,
messages);
mList.setAdapter(adapter);
}
}
SettingsDialog.java
public class SettingsDialog extends Dialog implements android.view.View.OnClickListener {
private MainActivity xmppClient;
public SettingsDialog(MainActivity xmppClient) {
super(xmppClient);
this.xmppClient = xmppClient;
}
protected void onStart() {
super.onStart();
setContentView(R.layout.settings);
getWindow().setFlags(4, 4);
setTitle("XMPP Settings");
Button ok = (Button) findViewById(R.id.ok);
ok.setOnClickListener(this);
}
public void onClick(View v) {
final String host = "chat.facebook.com";
final String port = ""+5222;
final String service = "chat.facebook.com";
final String username = "*****";
final String password = "****";
new Thread() {
public void run() {
// Create a connection
ConnectionConfiguration connConfig =new ConnectionConfiguration(host, Integer.parseInt(port), service);
connConfig.setSASLAuthenticationEnabled(true);
XMPPConnection connection = new XMPPConnection(connConfig);
try {
connection.connect();
Log.i("XMPPClient", "[SettingsDialog] Connected to " + connection.getHost());
} catch (Exception ex) {
Log.e("XMPPClient", "[SettingsDialog] Failed to connect to " + connection.getHost());
Log.e("XMPPClient", ex.toString());
xmppClient.setConnection(null);
}
try {
connection.login(username, password);
Log.i("XMPPClient", "Logged in as " + connection.getUser());
// Set the status to available
Presence presence = new Presence(Presence.Type.available);
connection.sendPacket(presence);
xmppClient.setConnection(connection);
} catch (XMPPException ex) {
Log.e("XMPPClient", "[SettingsDialog] Failed to log in as " + username);
Log.e("XMPPClient", ex.toString());
xmppClient.setConnection(null);
}
}
}.start();
dismiss();
}
private String getText(int id) {
EditText widget = (EditText) this.findViewById(id);
return widget.getText().toString();
}
}
SASLXFacebookPlatformMechanism.java
public class SASLXFacebookPlatformMechanism extends SASLMechanism
{
private static final String NAME = "X-FACEBOOK-PLATFORM";
private String apiKey = "";
private String applicationSecret = "";
private String sessionKey = "";
/**
* Constructor.
*/
public SASLXFacebookPlatformMechanism(SASLAuthentication saslAuthentication)
{
super(saslAuthentication);
}
#Override
protected void authenticate() throws IOException, XMPPException
{
getSASLAuthentication().send(new AuthMechanism(NAME, ""));
}
#Override
public void authenticate(String apiKeyAndSessionKey, String host,
String applicationSecret) throws IOException, XMPPException
{
if (apiKeyAndSessionKey == null || applicationSecret == null)
{
throw new IllegalArgumentException("Invalid parameters");
}
String[] keyArray = apiKeyAndSessionKey.split("\\|", 2);
if (keyArray.length < 2)
{
throw new IllegalArgumentException(
"API key or session key is not present");
}
this.apiKey = keyArray[0];
this.applicationSecret = applicationSecret;
this.sessionKey = keyArray[1];
this.authenticationId = sessionKey;
this.password = applicationSecret;
this.hostname = host;
String[] mechanisms = { "DIGEST-MD5" };
Map<String, String> props = new HashMap<String, String>();
this.sc =
Sasl.createSaslClient(mechanisms, null, "xmpp", host, props,
this);
authenticate();
}
#Override
public void authenticate(String username, String host, CallbackHandler cbh)
throws IOException, XMPPException
{
String[] mechanisms = { "DIGEST-MD5" };
Map<String, String> props = new HashMap<String, String>();
this.sc =
Sasl.createSaslClient(mechanisms, null, "xmpp", host, props,
cbh);
authenticate();
}
#Override
protected String getName()
{
return NAME;
}
#Override
public void challengeReceived(String challenge) throws IOException
{
byte[] response = null;
if (challenge != null)
{
String decodedChallenge = new String(Base64.decode(challenge));
Map<String, String> parameters = getQueryMap(decodedChallenge);
String version = "1.0";
String nonce = parameters.get("nonce");
String method = parameters.get("method");
long callId = new GregorianCalendar().getTimeInMillis();
String sig =
"api_key=" + apiKey + "call_id=" + callId + "method="
+ method + "nonce=" + nonce + "session_key="
+ sessionKey + "v=" + version + applicationSecret;
try
{
sig = md5(sig);
} catch (NoSuchAlgorithmException e)
{
throw new IllegalStateException(e);
}
String composedResponse =
"api_key=" + URLEncoder.encode(apiKey, "utf-8")
+ "&call_id=" + callId + "&method="
+ URLEncoder.encode(method, "utf-8") + "&nonce="
+ URLEncoder.encode(nonce, "utf-8")
+ "&session_key="
+ URLEncoder.encode(sessionKey, "utf-8") + "&v="
+ URLEncoder.encode(version, "utf-8") + "&sig="
+ URLEncoder.encode(sig, "utf-8");
response = composedResponse.getBytes("utf-8");
}
String authenticationText = "";
if (response != null)
{
authenticationText =
Base64.encodeBytes(response, Base64.DONT_BREAK_LINES);
}
// Send the authentication to the server
getSASLAuthentication().send(new Response(authenticationText));
}
private Map<String, String> getQueryMap(String query)
{
Map<String, String> map = new HashMap<String, String>();
String[] params = query.split("\\&");
for (String param : params)
{
String[] fields = param.split("=", 2);
map.put(fields[0], (fields.length > 1 ? fields[1] : null));
}
return map;
}
private String md5(String text) throws NoSuchAlgorithmException,
UnsupportedEncodingException
{
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(text.getBytes("utf-8"), 0, text.length());
return convertToHex(md.digest());
}
private String convertToHex(byte[] data)
{
StringBuilder buf = new StringBuilder();
int len = data.length;
for (int i = 0; i < len; i++)
{
int halfByte = (data[i] >>> 4) & 0xF;
int twoHalfs = 0;
do
{
if (0 <= halfByte && halfByte <= 9)
{
buf.append((char) ('0' + halfByte));
}
else
{
buf.append((char) ('a' + halfByte - 10));
}
halfByte = data[i] & 0xF;
} while (twoHalfs++ < 1);
}
return buf.toString();
}
#Override
protected String getAuthenticationText(String arg0, String arg1, String arg2) {
// TODO Auto-generated method stub
return null;
}
#Override
protected String getChallengeResponse(byte[] arg0) {
// TODO Auto-generated method stub
return null;
}
}
The code shows error stating
"The method send(String) in the type SASLAuthentication is not applicable for arguments(Response).The constructor Response(String) is undefined"
in the line-->"getSASLAuthentication().send(new Response(authenticationText));"
I am also confused on how to use this SASLXFacebookPlatformMechanism.java class in my MainActivity.class.I have been trying to get a sense of how it works but failing.A complete guideline on how to develop a xmpp facebook chat client using asmack library would be appreciated since the internet lacks enough documentation on it.Thanks.
[I have the apikeys and apitokens,so the empty string will not remain empty]

Error with xml HttpGet

I have an app that makes use of an xml obtained with a HttpGet. In the url of the xml request has a key that changes every hour, this key is obtained through another url.
Example: www.test.com/xml?hr=123456
The app tries to get the xml. If errors occur, get the key in another HttpGet and updates in the xml url.
In the emulator works perfectly, but not on the device. Already put a trace and the key is successfully updated. But the xml request error continues.
I tried to put "no cache" in HttpGet
HttpClient client = new DefaultHttpClient (httpParams);
HttpGet get = new HttpGet (url);
get.addHeader ("Cache-Control", "no-cache"); / / HTTP/1.1
get.addHeader ("Expires", "Sat, 26 Jul 1997 05:00:00 GMT");
but it did not work, is there anything that can be done?
My Complete Activity:
public class ShowActivity extends AdModctivity implements
bbbAndroidConstantes, OnItemClickListener, OnCheckedChangeListener {
private ProgressDialog dialog;
private Retf p;
private Handler handler = new Handler();
private Exception ex;
private CheckBox check;
private ParametrosTO parTO;
ParametrosDataBase parDB;
String ref;
String pId;
String logR;
String kId;
String ldesc;
TextView txtRef;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listaprevisoeslayout);
Bundle bundle = getIntent().getExtras();
parDB = new ParametrosDataBase(this);
parTO = parDB.listParametros();
pId = bundle.getString(VAR_P_ID);
ref = bundle.getString(VAR_P_REF);
logR = bundle.getString(VAR_LOGR);
kId = bundle.getString(VAR_KID);
ldesc = bundle.getString(VAR_LDESC);
txtRef = (TextView) findViewById(R.id.txtRef);
check = (CheckBox) findViewById(R.id.checkWidget);
WidgetDataBase wDb = new WidgetDataBase(this);
if (wDb.searchWidget(pId, kId) != null)
check.setChecked(true);
check.setOnCheckedChangeListener(this);
dialog = ProgressDialog.show(ShowActivity.this, "",
"Wait...", true);
if (!Utilities.chkStatus(ShowActivity.this))
return;
downloadInfo();
fillAdMod();
}
#Override
public void onItemClick(AdapterView parent, View v, int position, long id) {
}
private void downloadInfo() {
new Thread() {
#Override
public void run() {
boolean flag = false;
try {
p = Controller.getInstance().getRetf(parTO.getUrl(), pId, kId);
if ((p.getInfoP() == null) || (p.getInfoP().size() == 0)) {
flag = true;
String newUrl = getNewUrl();
Utilities.updateUrl(ShowActivity.this, newUrl);
parTO = parDB.listParametros();
p = Controller.getInstance().getRetf(newUrl, pId, kId);
}
refreshScreen();
} catch (Exception e) {
if (!flag) {
try {
String newUrl = getNewUrl();
Utilities.updateUrl(ShowActivity.this, newUrl);
parTO = parDB.listParametros();
p = Controller.getInstance().getRetf(newUrl, pId, kId);
refreshScreen();
} catch (Exception e1) {
ex = e1;
refreshScreenException();
}
}
else
{
ex = e;
refreshScreenException();
}
}
}
}.start();
}
/**
* Thread to close dialog and show information
*/
private void refreshScreen() {
handler.post(new Runnable() {
#Override
public void run() {
dialog.dismiss();
fillInfo();
}
});
}
/**
* Thread to close dialog and show exception
*/
private void refreshScreenException() {
handler.post(new Runnable() {
#Override
public void run() {
dialog.dismiss();
fillInfoExcecao();
}
});
}
/**
* Fill information on screen
*/
private void fillInfo() {
if (p == null) {
Toast.makeText(ShowActivity.this, MSG_SEM_Retf,
MSG_TIME_MILIS).show();
this.finish();
}
if ((p.getErro() != null) && (p.getErro().trim().length() > 0)) {
Toast.makeText(ShowActivity.this, p.getErro(),
MSG_TIME_MILIS).show();
this.finish();
}
if ((p.getPonto() == null) || (p.getPonto().size() == 0)) {
Toast.makeText(ShowActivity.this, MSG_SEM_Retf,
MSG_TIME_MILIS).show();
this.finish();
}
SimpleDateFormat spf = new SimpleDateFormat("HH:mm:ss");
long localTime = Long.parseLong(p.getLocalTime());
txtRef.setText(txtRef.getText() + " "
+ spf.format(new Date(localTime)));
RetfAdapter RetfAdapter = new RetfAdapter(this, p);
ListView lista = (ListView) findViewById(R.id.listView1);
lista.setAdapter(RetfAdapter);
lista.setOnItemClickListener(this);
}
/**
* Apresenta mensagem em caso de exceo
*/
private void fillInfoExcecao() {
if (ex instanceof bbbException) {
Toast.makeText(ShowActivity.this,
((bbbException) ex).getMessage(), MSG_TIME_MILIS).show();
ShowActivity.this.finish();
} else {
Toast.makeText(ShowActivity.this,
getString(R.string.msg_erroSistema), MSG_TIME_MILIS).show();
ShowActivity.this.finish();
}
}
#Override
public void onCheckedChanged(CompoundButton cb, boolean isChecked) {
PBean PBean = new PBean(pId, logR,
ref, kId, ldesc);
WidgetDataBase wDb = new WidgetDataBase(this);
if (isChecked)
wDb.addWidget(PBean);
else
wDb.deleteWidget(PBean);
}
private String getNewUrl() throws Exception
{
String newUrl = Utilities.getHttp(bbbAndroidConstantes.URL_HOST_HORARIOS);
return newUrl;
}
}

Categories

Resources