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

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);
}

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.

Getting Error java.lang.IllegalArgumentException: unexpected url

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 >.

Java/Android scoop

Why does Log.d("Test", "" + ListOfAttractions3.size() + ""); Return 0 when Log.d("Test2", "" + ListOfAttractions3.size() + ""); returns 2 even thoughDatabseRequest(); is called first? Some how Log 2 is also printed last but I can't see why?
Code:
public class Testlist extends Activity {
List<Attractions> ListOfAttractions3 = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_testlist);
DatabseRequest();
Log.d("Test", "" + ListOfAttractions3.size() + "");
}
/*private void reFreshDisplay(){
ListView listView2 = (ListView) findViewById(R.id.listView2);
ArrayAdapter<Attractions> adapter = new ArrayAdapter<Attractions>(this, android.R.layout.simple_list_item_1, ListOfAttractions3);
listView2.setAdapter(adapter);
adapter.notifyDataSetChanged();
}*/
private void DatabseRequest(){
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
int i = 0;
while(i < jsonArray.length()) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
boolean success;
if (jsonObject.getBoolean("success")) success = true;
else success = false;
if (success) {
String attractionname = jsonObject.getString("attractionname");
double lng = jsonObject.getDouble("longitude");
double lat = jsonObject.getDouble("latitude");
int Rating = jsonObject.getInt("rating");
Attractions attraction = new Attractions(attractionname, lng, lat, Rating);
ListOfAttractions3.add(attraction);
Log.d("Test2", "" + ListOfAttractions3.size() + "");
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(Testlist.this);
builder.setMessage("Connection to server Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
i++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
AttractionRequest attractionRequest = new AttractionRequest(responseListener);
RequestQueue queue2 = Volley.newRequestQueue(Testlist.this);
queue2.add(attractionRequest);
}
}

Why is my android activity performing so slow?

From the second you click on the notification activity button the program immediately starts acting slow. This screen for some reason takes minutes to scroll down in a very glitchy and drawn out manner. What can I do to speed up and smooth out my notification activity screen?
NotificationActivity:
public class NotificationActivity extends BaseActivity {
public static final String TAG = LoginActivity.class.getSimpleName();
private NotificationAdapter notificationAdapter;
private HeaderLayout headerLayout;
private FooterLayout footerLayout;
private SimpleGestureFilter detector;
private ListView mNotificationLv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
mNotificationLv = (ListView) findViewById(R.id.notification_lv);
mNotificationLv = (ListView) findViewById(R.id.notification_lv);
notificationAdapter = new NotificationAdapter(this);
notificationAdapter.setList(AtlasApplication.lstNotificationModels);
mNotificationLv.setAdapter(notificationAdapter);
// Detect touched area
detector = new SimpleGestureFilter(this,this);
}
#Override
protected void onResume() {
super.onResume();
List<NotificationModel> userModelList = AtlasApplication.lstNotificationModels;
notificationAdapter = new NotificationAdapter(this);
notificationAdapter.setList(userModelList);
mNotificationLv.setAdapter(notificationAdapter);
}
}
NotificationAdapter:
public class NotificationAdapter extends BaseAdapter{
private List<NotificationModel> lstNotificationModels;
private SQLiteAdapter sqLiteAdapter;
private Context context;
public NotificationAdapter(Context context) {
this.context = context; sqLiteAdapter=new SQLiteAdapter(context, this, new Dialog(context));
}
public void setList(List<NotificationModel> genres) {
this.lstNotificationModels = genres;
notifyDataSetChanged();
}
private class ViewHolder {
TextView mNotifiactionTypeTv, mNotifiactionTextTv, mNotifiactionTimeTv;
LinearLayout rowNotificationLl;
}
public void setRead(int i){
sqLiteAdapter.updateNotificationStatus(i, "read");
lstNotificationModels.get(i).setmNotificationStatus("read");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row_notification, null);
holder = new ViewHolder();
holder.rowNotificationLl = (LinearLayout) convertView.findViewById(R.id.row_notification_ll);
holder.mNotifiactionTextTv = (TextView) convertView.findViewById(R.id.notification_text_tv);
holder.mNotifiactionTimeTv = (TextView) convertView.findViewById(R.id.notification_time_tv);
holder.mNotifiactionTypeTv = (TextView) convertView.findViewById(R.id.notification_type_atv);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final NotificationModel notificationModel = lstNotificationModels.get(position);
final String newFullText = sqLiteAdapter.getFullText(notificationModel.getmLawId());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date currentDate = new Date();
Date notificationDate = new Date();
String timeElapsed = "moments ago.";
try {
notificationDate = simpleDateFormat.parse(notificationModel.getmNotificationTime().trim());
} catch(ParseException e){
}
long milliElapsed = currentDate.getTime() - notificationDate.getTime() + 14400000;
if(milliElapsed>=60000){
long minutesElapsed = milliElapsed/60000;
timeElapsed = minutesElapsed + " minutes ago.";
if(minutesElapsed>=60){
long hoursElapsed = minutesElapsed/60;
timeElapsed = hoursElapsed + " hours ago.";
if(hoursElapsed>=24){
long daysElapsed = hoursElapsed/60;
timeElapsed = daysElapsed + " days ago.";
if(daysElapsed>=7){
long weeksElapsed = daysElapsed/7;
timeElapsed = hoursElapsed + " weeks ago.";
if(weeksElapsed>=4){
long monthsElapsed = weeksElapsed/4;
timeElapsed = monthsElapsed + " months ago.";
if(daysElapsed>=365){
long yearsElapsed = daysElapsed/365;
timeElapsed = yearsElapsed + " years ago.";
}
}
}
}
}
}
holder.mNotifiactionTextTv.setText(Html.fromHtml(notificationModel.getmNotificationText().trim()));
holder.mNotifiactionTimeTv.setText(timeElapsed);
if (notificationModel.getmNotificationStatus().equalsIgnoreCase("unread")) {
convertView.findViewById(R.id.unread_vw).setVisibility(View.VISIBLE);
holder.rowNotificationLl.setBackgroundResource(R.color.black);
}
else {
convertView.findViewById(R.id.unread_vw).setVisibility(View.GONE);
holder.rowNotificationLl.setBackgroundResource(R.color.grad_light);
}
switch (notificationModel.getmNotificationType().toLowerCase()){
case "traffic":
holder.mNotifiactionTypeTv.setBackgroundResource(R.drawable.traffic_noti_bg);
holder.mNotifiactionTypeTv.setText("f");
holder.mNotifiactionTypeTv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
AtlasApplication.MenuTitle = Constants.CAT_TRAFFIC;
AtlasApplication.sCategoryModel = AtlasApplication.lstCategoryModels.get(0);
setRead(notificationModel.getmNotificaticationId());
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
} catch (Exception e) {
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
}
});
holder.mNotifiactionTextTv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
AtlasApplication.MenuTitle = Constants.CAT_TRAFFIC;
AtlasApplication.sCategoryModel = AtlasApplication.lstCategoryModels.get(0);
setRead(notificationModel.getmNotificaticationId());
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
catch(Exception e){
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
}
});
break;
case "law enforcement":
holder.mNotifiactionTypeTv.setBackgroundResource(R.drawable.enforcement_noti_bg);
holder.mNotifiactionTypeTv.setText("c");
holder.mNotifiactionTypeTv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
AtlasApplication.MenuTitle = Constants.CAT_ENFORCEMENT;
AtlasApplication.sCategoryModel = AtlasApplication.lstCategoryModels.get(1);
setRead(notificationModel.getmNotificaticationId());
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
} catch (Exception e) {
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
}
});
holder.mNotifiactionTextTv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
AtlasApplication.MenuTitle = Constants.CAT_ENFORCEMENT;
AtlasApplication.sCategoryModel = AtlasApplication.lstCategoryModels.get(1);
setRead(notificationModel.getmNotificaticationId());
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
catch(Exception e){
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
}
});
break;
case "alcohol":
holder.mNotifiactionTypeTv.setBackgroundResource(R.drawable.alcohal_noti_bg);
holder.mNotifiactionTypeTv.setText("a");
holder.mNotifiactionTypeTv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
AtlasApplication.MenuTitle = Constants.CAT_ALCOHOL;
AtlasApplication.sCategoryModel = AtlasApplication.lstCategoryModels.get(2);
setRead(notificationModel.getmNotificaticationId());
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
} catch (Exception e) {
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
}
});
holder.mNotifiactionTextTv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
AtlasApplication.MenuTitle = Constants.CAT_ALCOHOL;
AtlasApplication.sCategoryModel = AtlasApplication.lstCategoryModels.get(2);
setRead(notificationModel.getmNotificaticationId());
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
catch(Exception e){
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
}
});
break;
case "taxes":
holder.mNotifiactionTypeTv.setBackgroundResource(R.drawable.taxes_noti_bg);
holder.mNotifiactionTypeTv.setText("e");
holder.mNotifiactionTypeTv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
AtlasApplication.MenuTitle = Constants.CAT_TAXES;
AtlasApplication.sCategoryModel = AtlasApplication.lstCategoryModels.get(3);
setRead(notificationModel.getmNotificaticationId());
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
} catch (Exception e) {
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
}
});
holder.mNotifiactionTextTv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
AtlasApplication.MenuTitle = Constants.CAT_TAXES;
AtlasApplication.sCategoryModel = AtlasApplication.lstCategoryModels.get(3);
setRead(notificationModel.getmNotificaticationId());
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
} catch (Exception e) {
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
}
});
break;
case "guns":
holder.mNotifiactionTypeTv.setBackgroundResource(R.drawable.guns_noti_bg);
holder.mNotifiactionTypeTv.setText("b");
holder.mNotifiactionTypeTv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
AtlasApplication.MenuTitle = Constants.CAT_GUNS;
AtlasApplication.sCategoryModel = AtlasApplication.lstCategoryModels.get(4);
setRead(notificationModel.getmNotificaticationId());
AtlasApplication.lstLawsForLocation.get(1).setSelected(true);
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
} catch (Exception e) {
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
}
});
holder.mNotifiactionTextTv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
AtlasApplication.MenuTitle = Constants.CAT_GUNS;
AtlasApplication.sCategoryModel = AtlasApplication.lstCategoryModels.get(4);
setRead(notificationModel.getmNotificaticationId());
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
catch(Exception e){
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
}
});
break;
case "marijuana":
holder.mNotifiactionTypeTv.setBackgroundResource(R.drawable.marijuana_noti_bg);
holder.mNotifiactionTypeTv.setText("d");
holder.mNotifiactionTypeTv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
AtlasApplication.MenuTitle = Constants.CAT_MARIJUANA;
AtlasApplication.sCategoryModel = AtlasApplication.lstCategoryModels.get(5);
setRead(notificationModel.getmNotificaticationId());
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
} catch (Exception e) {
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
}
});
holder.mNotifiactionTextTv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
AtlasApplication.MenuTitle = Constants.CAT_MARIJUANA;
AtlasApplication.sCategoryModel = AtlasApplication.lstCategoryModels.get(5);
setRead(notificationModel.getmNotificaticationId());
AtlasApplication.lstLawsForLocation.get(1).setSelected(true);
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
} catch (Exception e) {
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
}
});
break;
default:
break;
}
FontLoader.setAtlasFont(holder.mNotifiactionTypeTv);
FontLoader.setRalewayRegularFont(holder.mNotifiactionTextTv, holder.mNotifiactionTimeTv);
holder.rowNotificationLl.setId(position);
holder.rowNotificationLl.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
return convertView;
}
}
SQLiteAdapter:
public class SQLiteAdapter {
private static final int DATABASE_VERSION = 1;
private static String DB_PATH;//= Environment.getExternalStorageDirectory() + "/" + context.getPackageName() + "/";
private SQLiteDatabase mSqLiteDatabase;
private Context mContext;
private Dialog mDialog;
private SQLiteDbQueryListener sqLiteDbQueryListener;
private ExceptionHandler exceptionHandler;
public SQLiteAdapter(Context c, SQLiteDbQueryListener listener, Dialog dialog) {
mContext = c;
sqLiteDbQueryListener = listener;
exceptionHandler = new ExceptionHandler(mContext, "SQLiteAdapter");
mDialog = dialog;
DB_PATH = Environment.getExternalStorageDirectory() + "/" + mContext.getPackageName() + "/";
//call it so db get copied from assets to sdcard
//call it so db get copied from assets to sdcard
openToRead();
close();
}
public void updateLaw(int lawID, String newSummary, String newFullText){
int tagID = getTagID(lawID);
String tagName = getTagName(tagID);
int categoryID = getCategoryID(tagID);
String categoryName = getCategoryName(categoryID);
String location;
location = getLocationName(getLocationID(lawID));
if (location.toLowerCase().equals(AtlasApplication.sHometownSelected.getLocationName().toLowerCase())) {
location = "your current state";
} else if (location.toLowerCase().equals(AtlasApplication.sHometownSelected.getLocationName().toLowerCase())) {
location = "your home state";
}
openToWrite();
ContentValues contentValues = new ContentValues();
contentValues.put(Constants.KEY_SUMMARY, newSummary);
if(newFullText!=null)
contentValues.put(Constants.KEY_FULL_TEXT, newFullText);
mSqLiteDatabase.update(Constants.TABLE_LAW, contentValues, Constants.KEY_LAW_ID + "=" + lawID, null);
close();
insertNotification(lawID, categoryName, tagName + " has changed in " + location + ".");
}
public int getCategoryID(int tagID){
openToRead();
int categoryID = 0;
String Query = "SELECT * from " + Constants.TABLE_CATEGORY_TAG;
Cursor cursor = mSqLiteDatabase.rawQuery(Query, null);
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
if (cursor.getInt(cursor.getColumnIndex(Constants.KEY_TAG_ID)) == tagID) {
int indexCategoryID = cursor.getColumnIndex(Constants.KEY_CATEGORY_ID);
categoryID = cursor.getInt(indexCategoryID);
}
cursor.moveToNext();
}
}
close();
return categoryID;
}
public String getCategoryName(int categoryID){
String categoryName = "";
openToRead();
String Query = "SELECT * from " + Constants.TABLE_CATEGORY;
Cursor cursor = mSqLiteDatabase.rawQuery(Query, null);
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
if (cursor.getInt(cursor.getColumnIndex(Constants.KEY_CATEGORY_ID)) == categoryID) {
int indexCategoryName = cursor.getColumnIndex(Constants.KEY_CATEGORY_NAME);
categoryName = cursor.getString(indexCategoryName);
}
cursor.moveToNext();
}
}
close();
return categoryName.toLowerCase();
}
public int getLocationID(int lawID){
openToRead();
String Query = "SELECT * from " + Constants.TABLE_LAW_LOCATION;
Cursor cursor = mSqLiteDatabase.rawQuery(Query, null);
int locationID = 0;
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
try {
if(cursor.getInt(cursor.getColumnIndex(Constants.KEY_LAW_ID)) == lawID) {
int indexTagID = cursor.getColumnIndex(Constants.KEY_LOCATION_ID);
locationID = cursor.getInt(indexTagID);
}
} catch (Exception e) {
exceptionHandler.alert(e, "getLocationID()");
}
cursor.moveToNext();
}
}
close();
return locationID;
}
public String getLocationName(int locationID){
openToRead();
String Query = "SELECT * from " + Constants.TABLE_LOCATION;
Cursor cursor = mSqLiteDatabase.rawQuery(Query, null);
String locationName = "";
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
if(cursor.getInt(cursor.getColumnIndex(Constants.KEY_LOCATION_ID)) == locationID) {
int indexTagID = cursor.getColumnIndex(Constants.KEY_LOCATION_NAME);
locationName = cursor.getString(indexTagID);
}
cursor.moveToNext();
}
}
close();
return locationName;
}
public int getTagID(int lawID){
openToRead();
String Query = "SELECT * from " + Constants.TABLE_LAW_TAG;
Cursor cursor = mSqLiteDatabase.rawQuery(Query, null);
int tagID = 0;
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
if(cursor.getInt(cursor.getColumnIndex(Constants.KEY_LAW_ID)) == lawID) {
int indexTagID = cursor.getColumnIndex(Constants.KEY_TAG_ID);
tagID = cursor.getInt(indexTagID);
cursor.moveToNext();
}
}
close();
return tagID;
}
public String getTagName(int tagID){
openToRead();
String tagName = "";
String Query = "SELECT * from " + Constants.TABLE_TAG;
Cursor cursor = mSqLiteDatabase.rawQuery(Query, null);
if(cursor.moveToFirst()){
while (cursor.isAfterLast() == false) {
try {
if(cursor.getInt(cursor.getColumnIndex(Constants.KEY_TAG_ID)) == tagID) {
int indexTagName = cursor.getColumnIndex(Constants.KEY_TAG_NAME);
tagName = cursor.getString(indexTagName);
}
} catch (Exception e) {
exceptionHandler.alert(e, "getTagName()");
}
cursor.moveToNext();
}
}
close();
return tagName;
}
public void insertNotification(int lawID, String type, String text){
openToWrite();
try {
ContentValues contentValues = new ContentValues();
contentValues.put(Constants.KEY_LAW_ID, lawID);
contentValues.put(Constants.KEY_NOTIFICATION_TYPE, type);
contentValues.put(Constants.KEY_NOTIFICATION_TEXT, text);
contentValues.put(Constants.KEY_NOTIFICATION_STATUS, "unread");
mSqLiteDatabase.insert(Constants.TABLE_NOTIFICATION, null, contentValues);
}
catch(Exception e){
exceptionHandler.alert(e, "insertNotification()");
}
close();
}
public void dropNotifications(){
openToWrite();
try{
mSqLiteDatabase.execSQL("DROP TABLE IF EXISTS notification");
}
catch(Exception e){
}
close();
}
public void updateNotificationStatus(int notificationID, String status){
openToWrite();
try {
ContentValues contentValues = new ContentValues();
contentValues.put(Constants.KEY_NOTIFICATION_STATUS, status);
mSqLiteDatabase.update(Constants.TABLE_NOTIFICATION, contentValues, Constants.KEY_NOTIFICATION_ID + "=" + notificationID, null);
}
catch(Exception e){
exceptionHandler.alert(e, "updateNotificationStatus()");
}
close();
}
public String getNotificationStatus(int notificationID){
openToRead();
String Query = "SELECT * FROM " + Constants.TABLE_NOTIFICATION + " WHERE " + Constants.KEY_NOTIFICATION_ID + "=" + notificationID;
Cursor cursor = mSqLiteDatabase.rawQuery(Query, null);
String notificationStatus = "";
if(cursor.moveToFirst()){
while (cursor.isAfterLast() == false) {
try {
if(cursor.getInt(cursor.getColumnIndex(Constants.KEY_NOTIFICATION_ID)) == notificationID) {
int indexNotificationStatus = cursor.getColumnIndex(Constants.KEY_NOTIFICATION_STATUS);
notificationStatus = cursor.getString(indexNotificationStatus);
}
} catch (Exception e) {
exceptionHandler.alert(e, "getNotificationStatus()");
}
cursor.moveToNext();
}
}
close();
return notificationStatus;
}
public int getNotificationId(int lawID, String time){
openToRead();
int notificationId = 0;
String query = "SELECT * FROM " + Constants.TABLE_NOTIFICATION +
" WHERE " + Constants.KEY_NOTIFICATION_TIME + " = " + time;
Cursor cursor = mSqLiteDatabase.rawQuery(query, null);
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
int indexNotificationID = cursor.getColumnIndex(Constants.KEY_NOTIFICATION_ID);
notificationId = cursor.getInt(indexNotificationID);
}
}
close();
return notificationId;
}
public List<NotificationModel> getNotificationList(){
List<NotificationModel> lstNotifications = new ArrayList<NotificationModel>();
openToRead();
String Query = "SELECT * from " + Constants.TABLE_NOTIFICATION;
Cursor cursor = mSqLiteDatabase.rawQuery(Query, null);
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
try {
int indexNotificationID = cursor.getColumnIndex(Constants.KEY_NOTIFICATION_ID);
int indexLawID = cursor.getColumnIndex(Constants.KEY_LAW_ID);
int indexNotificationTime = cursor.getColumnIndex(Constants.KEY_NOTIFICATION_TIME);
int indexNotificationType = cursor.getColumnIndex(Constants.KEY_NOTIFICATION_TYPE);
int indexNotificationText = cursor.getColumnIndex(Constants.KEY_NOTIFICATION_TEXT);
int indexNotificationStatus = cursor.getColumnIndex(Constants.KEY_NOTIFICATION_STATUS);
int notificationID = cursor.getInt(indexNotificationID);
int lawID = indexLawID;
String notificationTime = cursor.getString(indexNotificationTime);
String notificationType = cursor.getString(indexNotificationType);
String notificationText = cursor.getString(indexNotificationText);
String notificationStatus = cursor.getString(indexNotificationStatus);
lstNotifications.add(new NotificationModel(notificationID, lawID, notificationType, notificationText, notificationTime, notificationStatus));
} catch (Exception e) {
exceptionHandler.alert(e, "getNotificationList()");
}
cursor.moveToNext();
}
}
close();
Collections.reverse(lstNotifications);
return lstNotifications;
}
}
MainActivity:
sqLiteAdapter.updateLaw(962, "test", "test");
The issue you described is pretty hard to detect in this code but here is a list of notes/best practices you should take into consideration:
You should ALWAYS do your DB queries on a secondary thread and not on your main thread (Try an AsyncTask).
you have a SimpleGestureFilter which I can't say what is for or what it does. If you have some ugly logic there, that may affect scrolling.
You create tons of LayoutInflater variables in your getView() method which is pretty bad. Make it a global variable and initialize it in the Adapter's constructor. Do you have an idea of how many times the getView() method gets called when you scroll? Put a log there and analyse :).
Definitely not hold an instance to your SQLiteAdapter object in the adapter. Do that in your activity and update your adapter when you need it. The Adapter should always be the representation of your data and not doing having logic and whatever else.
Not sure what the FontLoader does but if you read a font from the assets every time the getView() is called, you have a huuuge problem. Try to load fonts as few times as possible because that's a heavy operation.
Never catch general Exceptions. Try to focus on the specific ones.

while updating(editing) its not taking the old audio file name

having one text and audio(recording) and saving the name and path in db.while clicking the name that audio has to play its playing also.But while editing if i supposed to change the name alone,it will not take the old file name of the respective one,its make that one as null.
How to take the old audio file name if people will not update the audio(recording)
audioactivity.java
private void saveState() {
String audioname = et1.getText().toString();
String audiofilename = gfilename;
String audiocount = et2.getText().toString();
if(audiocount.equals("")){
audiocount ="1";
}
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String audiodate = sdf.format(new Date());
if (mRowId == null || mRowId.longValue() == 0)
{
long id = mDbHelper.createProject4(audioname, audiofilename, audiocount, audiodate);
if (id > 0) {
mRowId = id;
}
} else {
audiofilename=gfilename;
mDbHelper.updateProject4(mRowId, audioname, audiofilename, audiocount,audiodate);
}
}
public View.OnClickListener btnClick = new View.OnClickListener()
{
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btnStart:{
AppLog.logString("Start Recording");
enableButtons(true);
startRecording();
break;
}
case R.id.btnstop:{
AppLog.logString("Start Recording");
enableButtons(false);
stopRecording();
break;
}
}
}
};
public MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() {
#Override
public void onError(MediaRecorder mr, int what, int extra) {
AppLog.logString("Error: " + what + ", " + extra);
}
};
public MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() {
#Override
public void onInfo(MediaRecorder mr, int what, int extra) {
AppLog.logString("Warning: " + what + ", " + extra);
}
};
public void setButtonHandlers() {
((Button)findViewById(R.id.btnStart)).setOnClickListener(btnClick);
((Button)findViewById(R.id.btnstop)).setOnClickListener(btnClick);
}
public void enableButton(int id,boolean isEnable){
((Button)findViewById(id)).setEnabled(isEnable);
}
public void enableButtons(boolean isRecording) {
enableButton(R.id.btnStart,!isRecording);
enableButton(R.id.btnstop,isRecording);
}
#SuppressLint("NewApi")
private void startRecording(){
//displayFormatDialog();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
String formats[] = {"MPEG 4", "3GPP", "AMR"};
builder.setTitle(getString(R.string.choose_format_title))
.setSingleChoiceItems(formats, currentFormat, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
currentFormat = which;
dialog.dismiss();
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(output_formats[currentFormat]);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(getFilename());
//recorder.setOnErrorListener(errorListener);
//recorder.setOnInfoListener(infoListener);
try {
recorder.prepare();
recorder.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
})
.show();
}
private void stopRecording(){
if(null != recorder)
{
//mDbHelper.updateProject4FileName(mRowId, gfilename);
recorder.stop();
recorder.reset();
recorder.release();
recorder = null;
}
else
{
recorder.stop();
recorder.release();
}
}
public String getFilename(){
String filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath,AUDIO_RECORDER_FOLDER);
if(!file.exists()){
file.mkdirs();
}
gfilename = (file.getAbsolutePath() + "/" + System.currentTimeMillis() + file_exts[currentFormat]);
return (gfilename);
}
#Override
public void onCompletion (MediaPlayer arg0)
{
}
public void playSong(String gfilename){
// Play song
try
{
mp.reset();
mp.setDataSource(gfilename);
mp.prepare();
mp.start();
// Changing Button Image to pause image
btnPlay.setImageResource(R.drawable.btn_pause);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I checked in debugging also,if we didnt update the recording its taking that place as null only.
Here i attached my db updated code also
public boolean updateProject4(long _id, String audioname, String audiofilename,String audiocount,String audiodate) {
ContentValues args = new ContentValues();
args.put(CATEGORY_COLUMN_AUDIONAME, audioname );
args.put(CATEGORY_COLUMN_AUDIOFILENAME, audiofilename );
args.put(CATEGORY_COLUMN_AUDIOCOUNT, audiocount );
args.put(CATEGORY_COLUMN_AUDIODATE, audiodate );
return mDb.update(DATABASE_TABLE_AUDIOPRAYER, args, CATEGORY_COLUMN_ID4 + "=" + _id, null) > 0;
}
Actually i got the way for my question.
Want to fetchfile from db if my filename becomes null while updating
private void saveState() {
String audioname = et1.getText().toString();
String audiofilename = gfilename;
String audiocount = et2.getText().toString();
if(audiocount.equals("")){
audiocount ="1";
}
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String audiodate = sdf.format(new Date());
//String reqname= spin.getSelectedItem().toString();
//Log.i(" save state mathod "," values are "+title+Desc+Body+reqname);
if (mRowId == null || mRowId.longValue() == 0)
{
long id = mDbHelper.createProject4(audioname, audiofilename, audiocount, audiodate);
if (id > 0) {
mRowId = id;
}
} else {
if(audiofilename.equals("")){
Cursor filename = mDbHelper.fetchProject4FileName(mRowId, audiofilename);
startManagingCursor(filename);
gfilename =filename.getString(filename.getColumnIndexOrThrow(GinfyDbAdapter.CATEGORY_COLUMN_AUDIOFILENAME));
//mDbHelper.fetchProject4FileName(mRowId, audiofilename);
audiofilename = gfilename;
mDbHelper.updateProject4(mRowId, audioname, audiofilename, audiocount,audiodate);
}
else
{
audiofilename = gfilename;
mDbHelper.updateProject4(mRowId, audioname, audiofilename, audiocount,audiodate);
}
}
we have to fetch the filename from db and check whether our audiofilename is null means,we have to set the older filename

Categories

Resources