How to decode JSON data sent to server by TripTracker? - java

I am using a PHP MySQL server model. I want to decode the JSON data that is sent to the server by this code. Any help would be appreciated. The app sends current GPS coordinates to inputed server as JSON array object. I would like to decode it to share with other android users. Thanks a lot. This is the Android code.
public class TrackerService extends Service {
private static final String TAG = "TripTracker/Service";
private final String updatesCache = "updates.cache";
public static TrackerService service;
private NotificationManager nm;
private Notification notification;
private static boolean isRunning = false;
private String freqString;
private int freqSeconds;
private String endpoint;
private final int MAX_RING_SIZE = 15;
private LocationListener locationListener;
private AlarmManager alarmManager;
private PendingIntent pendingAlarm;
private static volatile PowerManager.WakeLock wakeLock;
private AsyncTask httpPoster;
ArrayList<LogMessage> mLogRing = new ArrayList<LogMessage>();
ArrayList<Messenger> mClients = new ArrayList<Messenger>();
ArrayList<List> mUpdates = new ArrayList<List>();
final ReentrantReadWriteLock updateLock = new ReentrantReadWriteLock();
final Messenger mMessenger = new Messenger(new IncomingHandler());
static final int MSG_REGISTER_CLIENT = 1;
static final int MSG_UNREGISTER_CLIENT = 2;
static final int MSG_LOG = 3;
static final int MSG_LOG_RING = 4;
#Override
public IBinder onBind(Intent intent) {
return mMessenger.getBinder();
}
#Override
public void onCreate() {
super.onCreate();
TrackerService.service = this;
endpoint = Prefs.getEndpoint(this);
freqSeconds = 0;
freqString = null;
freqString = Prefs.getUpdateFreq(this);
if (freqString != null && !freqString.equals("")) {
try {
Pattern p = Pattern.compile("(\\d+)(m|h|s)");
Matcher m = p.matcher(freqString);
m.find();
freqSeconds = Integer.parseInt(m.group(1));
if (m.group(2).equals("h"))
freqSeconds *= (60 * 60);
else if (m.group(2).equals("m"))
freqSeconds *= 60;
}
catch (Exception e) {
}
}
if (endpoint == null || endpoint.equals("")) {
logText("invalid endpoint, stopping service");
stopSelf();
}
if (freqSeconds < 1) {
logText("invalid frequency (" + freqSeconds + "), stopping " +
"service");
stopSelf();
}
readCache();
showNotification();
isRunning = true;
/* we're not registered yet, so this will just log to our ring buffer,
* but as soon as the client connects we send the log buffer anyway */
logText("service started, requesting location update every " +
freqString);
/* findAndSendLocation() will callback to this */
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
sendLocation(location);
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
/* we don't need to be exact in our frequency, try to conserve at least
* a little battery */
alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Intent i = new Intent(this, AlarmBroadcast.class);
pendingAlarm = PendingIntent.getBroadcast(this, 0, i, 0);
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(), freqSeconds * 1000, pendingAlarm);
}
#Override
public void onDestroy() {
super.onDestroy();
if (httpPoster != null)
httpPoster.cancel(true);
try {
LocationManager locationManager = (LocationManager)
this.getSystemService(Context.LOCATION_SERVICE);
locationManager.removeUpdates(locationListener);
}
catch (Exception e) {
}
/* kill persistent notification */
nm.cancelAll();
if (pendingAlarm != null)
alarmManager.cancel(pendingAlarm);
isRunning = false;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
/* must be done inside of updateLock */
public void cacheUpdates() {
OutputStreamWriter cacheStream = null;
try {
FileOutputStream cacheFile = TrackerService.this.openFileOutput(
updatesCache, Activity.MODE_PRIVATE);
cacheStream = new OutputStreamWriter(cacheFile, "UTF-8");
/* would be nice to just serialize mUpdates but it's not
* serializable. create a json array of json objects, each object
* having each key/value pair of one location update. */
JSONArray ja = new JSONArray();
for (int i = 0; i < mUpdates.size(); i++) {
List<NameValuePair> pair = mUpdates.get(i);
JSONObject jo = new JSONObject();
for (int j = 0; j < pair.size(); j++) {
try {
jo.put(((NameValuePair)pair.get(j)).getName(),
pair.get(j).getValue());
}
catch (JSONException e) {
}
}
ja.put(jo);
}
cacheStream.write(ja.toString());
cacheFile.getFD().sync();
}
catch (IOException e) {
Log.w(TAG, e);
}
finally {
if (cacheStream != null) {
try {
cacheStream.close();
}
catch (IOException e) {
}
}
}
}
/* read json cache into mUpdates */
public void readCache() {
updateLock.writeLock().lock();
InputStreamReader cacheStream = null;
try {
FileInputStream cacheFile = TrackerService.this.openFileInput(
updatesCache);
StringBuffer buf = new StringBuffer("");
byte[] bbuf = new byte[1024];
int len;
while ((len = cacheFile.read(bbuf)) != -1)
buf.append(new String(bbuf));
JSONArray ja = new JSONArray(new String(buf));
mUpdates = new ArrayList<List>();
for (int j = 0; j < ja.length(); j++) {
JSONObject jo = ja.getJSONObject(j);
List<NameValuePair> nvp = new ArrayList<NameValuePair>(2);
Iterator<String> i = jo.keys();
while (i.hasNext()) {
String k = (String)i.next();
String v = jo.getString(k);
nvp.add(new BasicNameValuePair(k, v));
}
mUpdates.add(nvp);
}
if (mUpdates.size() > 0)
logText("read " + mUpdates.size() + " update" +
(mUpdates.size() == 1 ? "" : "s") + " from cache");
}
catch (JSONException e) {
}
catch (FileNotFoundException e) {
}
catch (IOException e) {
Log.w(TAG, e);
}
finally {
if (cacheStream != null) {
try {
cacheStream.close();
}
catch (IOException e) {
}
}
}
updateLock.writeLock().unlock();
}
/* called within wake lock from broadcast receiver, but assert that we have
* it so we can keep it longer when we return (since the location request
* uses a callback) and then free it when we're done running through the
* queue */
public void findAndSendLocation() {
if (wakeLock == null) {
PowerManager pm = (PowerManager)this.getSystemService(
Context.POWER_SERVICE);
/* we don't need the screen on */
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"triptracker");
wakeLock.setReferenceCounted(true);
}
if (!wakeLock.isHeld())
wakeLock.acquire();
LocationManager locationManager = (LocationManager)
this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER,
locationListener, null);
}
public static boolean isRunning() {
return isRunning;
}
private void showNotification() {
nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
notification = new Notification(R.drawable.icon,
"Trip Tracker Started", System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
notification.setLatestEventInfo(this, "Trip Tracker",
"Sending location every " + freqString, contentIntent);
notification.flags = Notification.FLAG_ONGOING_EVENT;
nm.notify(1, notification);
}
private void updateNotification(String text) {
if (nm != null) {
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
notification.setLatestEventInfo(this, "Trip Tracker", text,
contentIntent);
notification.when = System.currentTimeMillis();
nm.notify(1, notification);
}
}
public void logText(String log) {
LogMessage lm = new LogMessage(new Date(), log);
mLogRing.add(lm);
if (mLogRing.size() > MAX_RING_SIZE)
mLogRing.remove(0);
updateNotification(log);
for (int i = mClients.size() - 1; i >= 0; i--) {
try {
Bundle b = new Bundle();
b.putString("log", log);
Message msg = Message.obtain(null, MSG_LOG);
msg.setData(b);
mClients.get(i).send(msg);
}
catch (RemoteException e) {
/* client is dead, how did this happen */
mClients.remove(i);
}
}
}
/* flatten an array of NameValuePairs into an array of
* locations[0]latitude, locations[1]latitude, etc. */
public List<NameValuePair> getUpdatesAsArray() {
List<NameValuePair> pairs = new ArrayList<NameValuePair>(2);
for (int i = 0; i < mUpdates.size(); i++) {
List<NameValuePair> pair = mUpdates.get(i);
for (int j = 0; j < pair.size(); j++)
pairs.add(new BasicNameValuePair("locations[" + i + "][" +
((NameValuePair)pair.get(j)).getName() + "]",
pair.get(j).getValue()));
}
return pairs;
}
public int getUpdatesSize() {
return mUpdates.size();
}
public void removeUpdate(int i) {
mUpdates.remove(i);
}
private void sendLocation(Location location) {
List<NameValuePair> pairs = new ArrayList<NameValuePair>(2);
pairs.add(new BasicNameValuePair("time",
String.valueOf(location.getTime())));
pairs.add(new BasicNameValuePair("latitude",
String.valueOf(location.getLatitude())));
pairs.add(new BasicNameValuePair("longitude",
String.valueOf(location.getLongitude())));
pairs.add(new BasicNameValuePair("speed",
String.valueOf(location.getSpeed())));
/* push these pairs onto the queue, and only run the poster if another
* one isn't running already (if it is, it will keep running through
* the queue until it's empty) */
updateLock.writeLock().lock();
mUpdates.add(pairs);
int size = service.getUpdatesSize();
cacheUpdates();
updateLock.writeLock().unlock();
logText("location " +
(new DecimalFormat("#.######").format(location.getLatitude())) +
", " +
(new DecimalFormat("#.######").format(location.getLongitude())) +
(size <= 1 ? "" : " (" + size + " queued)"));
if (httpPoster == null ||
httpPoster.getStatus() == AsyncTask.Status.FINISHED)
(httpPoster = new HttpPoster()).execute();
}
class IncomingHandler extends Handler {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_REGISTER_CLIENT:
mClients.add(msg.replyTo);
/* respond with our log ring to show what we've been up to */
try {
Message replyMsg = Message.obtain(null, MSG_LOG_RING);
replyMsg.obj = mLogRing;
msg.replyTo.send(replyMsg);
}
catch (RemoteException e) {
}
break;
case MSG_UNREGISTER_CLIENT:
mClients.remove(msg.replyTo);
break;
default:
super.handleMessage(msg);
}
}
}
/* Void as first arg causes a crash, no idea why
E/AndroidRuntime(17157): Caused by: java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.lang.Void[]
*/
class HttpPoster extends AsyncTask<Object, Void, Boolean> {
#Override
protected Boolean doInBackground(Object... o) {
TrackerService service = TrackerService.service;
int retried = 0;
int max_retries = 4;
while (true) {
if (isCancelled())
return false;
boolean failed = false;
updateLock.writeLock().lock();
List<NameValuePair> pairs = service.getUpdatesAsArray();
int pairSize = service.getUpdatesSize();
updateLock.writeLock().unlock();
AndroidHttpClient httpClient =
AndroidHttpClient.newInstance("TripTracker");
try {
HttpPost post = new HttpPost(endpoint);
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse resp = httpClient.execute(post);
int httpStatus = resp.getStatusLine().getStatusCode();
if (httpStatus == 200) {
/* all good, we can remove everything we've sent from
* the queue (but not just clear it, in case another
* one jumped onto the end while we were here) */
updateLock.writeLock().lock();
for (int i = pairSize - 1; i >= 0; i--)
service.removeUpdate(i);
updateLock.writeLock().unlock();
}
else {
logText("POST failed to " + endpoint + ": got " +
httpStatus + " status");
failed = true;
}
}
catch (Exception e) {
logText("POST failed to " + endpoint + ": " + e);
Log.w(TAG, e);
failed = true;
}
finally {
if (httpClient != null)
httpClient.close();
}
if (failed) {
/* if our initial request failed, snooze for a bit and try
* again, the server might not be reachable */
SystemClock.sleep(15 * 1000);
if (++retried > max_retries) {
/* give up since we're holding the wake lock open for
* too long. we'll get it next time, champ. */
logText("too many failures, retrying later (queue " +
"size " + service.getUpdatesSize() + ")");
break;
}
}
else
retried = 0;
int q = 0;
updateLock.writeLock().lock();
q = service.getUpdatesSize();
cacheUpdates();
updateLock.writeLock().unlock();
if (q == 0)
break;
/* otherwise, run through the rest of the queue */
}
return false;
}
protected void onPostExecute(Boolean b) {
if (wakeLock != null && wakeLock.isHeld())
wakeLock.release();
}
}
}

You can decode the data using json_decode()
<?php
$json = ""; // JSON data
$json_obj = json_decode($json); // As Object
$json_arr = json_decide($json,true) // As Array
var_dump($json_obj);
print_r($json_arr);
// Store Array to database using serialize function
$data = serialize($json_array); // Array will be converted into string
?>

Related

Android Studio, there's an error retrieving schedule information

Currently, I have to click on the screen to get the schedule information.
I think the calender and db are loaded at the same time, but the speed at which db is loaded is slow, so it doesn't appear on the calendar right away.
But when I enter the schedule screen, I want to have the schedule information from DB appear at the bottom.
Calendar Activity: Connect to the calendar adapter and load data from the DB. When I checked on the console, the DB information is immediately imported when you enter the schedule screen.
Calendar Adapter : Bind data to the created ViewHolder, color on date (BLUE)
`
public class CalendarActivity extends AppCompatActivity implements CalendarAdapter.OnItemListener
{
#Override
protected void onCreate(Bundle savedInstanceState) {
initWidgets();
CalendarUtils.selectedDate = LocalDate.now();
setMonthView();
// get data from DB
GetData task = new GetData();
task.execute(userID);
}
private void setMonthView() {
//년 월 텍스트뷰
monthYearText.setText(monthYearFromDate(CalendarUtils.selectedDate));
//해당 월 날짜 가져오기
ArrayList<LocalDate> daysInMonth = daysInMonthArray(CalendarUtils.selectedDate);
CalendarAdapter calendarAdapter = new CalendarAdapter(daysInMonth, this);
//레이아웃 설정, 열 7개
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 7);
calendarRecyclerView.setLayoutManager(layoutManager);
calendarRecyclerView.setAdapter(calendarAdapter);
setEventAdapter();
}
// 이벤트 Adapter 제공
private void setEventAdapter() {
//ID 로 목록 찾고 리스트 호출
ArrayList<Event> dailyEvents = eventsForDate(CalendarUtils.selectedDate);
EventAdapter eventAdapter = new EventAdapter(this, this, dailyEvents);
eventListView.setAdapter(eventAdapter);
}
// 새로운 이벤트 생성
public void newEventAction(View view) {
startActivity(new Intent(CalendarActivity.this, EventEditActivity.class));
}
// 재개될 때마다 다시 로드되도록 EventAdapter 호출
//Activity가 사용자와 상호작용하기 바로 전에 호출됨
#Override
protected void onResume() {
super.onResume();
setEventAdapter();
eventsList.clear();
}
// 주어진 날짜에 대한 모든 이벤트 반환
public static ArrayList<Event> eventsForDate(LocalDate date) {
events = new ArrayList<>();
for (int k = 0; k < eventsList.size(); k++) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String selectDate1 = date.toString(); //현재누른날짜
String startDate1 = eventsList.get(k).getStartdate(); //시작날짜
String endDate1 = eventsList.get(k).getEnddate(); //종료날짜
Date selectDate = null;
try {
selectDate = dateFormat.parse(selectDate1);
Date startDate = dateFormat.parse(startDate1);
Date endDate = dateFormat.parse(endDate1);
int result1 = selectDate.compareTo(startDate); // curr > d1
int result2 = selectDate.compareTo(endDate);
// 조건이 맞을때
if ((result1 >= 0) && (result2 <= 0)) //선택한 날짜가 시작날짜랑 같거나 크고 & 앤드날짜보다 작거나 같으면
events.add(eventsList.get(k)); //items.get(k)가 events 어레이에 더해짐
} catch (ParseException e) {
e.printStackTrace();
}
}
return events;
}
// 주어진 날짜에 대한 ID 반환 - 수정인지 판단
public static int eventsForID(String passedID) {
for (int i = 0; i < eventsList.size(); i++) {
String ID = eventsList.get(i).getID();
if(ID != null && passedID != null) {
//각각 일치하면 0 리턴하므로 합계 0일경우 모두 일치한다.
if (passedID.compareTo(ID)== 0) {
Log.e("compare", "ok");
return 1;
}
}
}
return 0;
}
// DB에서 이벤트 가져오기
class GetData extends AsyncTask<String, Void, String> {
ProgressDialog progressDialog;
String errorString = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(CalendarActivity.this,
"Please Wait", null, true, true);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
Log.d(TAG, "response - " + result);
if (result != null) {
mJsonString = result;
showResult();
}
}
#Override
protected String doInBackground(String... params) {
String searchKeyword1 = params[0];
String serverURL = "http://"+IP_ADDRESS+"/event_query.php";
String postParameters = "userID=" + searchKeyword1;
Log.d(TAG, "userID_event : " + searchKeyword1);
try {
URL url = new URL(serverURL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(5000);
httpURLConnection.setConnectTimeout(5000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.connect();
OutputStream outputStream = httpURLConnection.getOutputStream();
outputStream.write(postParameters.getBytes("UTF-8"));
outputStream.flush();
outputStream.close();
int responseStatusCode = httpURLConnection.getResponseCode();
Log.d(TAG, "response code - " + responseStatusCode);
InputStream inputStream;
if (responseStatusCode == HttpURLConnection.HTTP_OK) {
inputStream = httpURLConnection.getInputStream();
} else {
inputStream = httpURLConnection.getErrorStream();
}
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
bufferedReader.close();
return sb.toString().trim();
} catch (Exception e) {
Log.d(TAG, "getData: Error ", e);
errorString = e.toString();
return null;
}
}
// DB에서 array로 데이터 가져옴
public void showResult() {
try {
JSONObject jsonObject = new JSONObject(mJsonString);
JSONArray jsonArray = jsonObject.getJSONArray(TAG_JSON);
// eventsList에 저장하기 전 저장되어있던 List를 clear한 후 가져온다
eventsList.clear();
for (int i = 0; i < jsonArray.length(); i++) {
if (jsonArray.length() != 0) {
JSONObject item = jsonArray.getJSONObject(i);
Log.d(TAG, "JSONObject : " + item);
// 해당 키워드로 DB에서 데이터를 가져온다(ID, title...)
ID = item.getString("ID");
title = item.getString("title");
startdate = item.getString("startdate");
enddate = item.getString("enddate");
alarmactive = item.getString("alarmactive");
// 가져온 데이터 eventsList에 저장
eventsList.add(new Event(ID, title, startdate, enddate, alarmactive));
Log.d(TAG, "eventsList : " + eventsList.toString());
}
}
} catch (JSONException e) {
Log.d(TAG, "showResult_member : ", e);
}
}
}
}
`
`
class CalendarAdapter extends RecyclerView.Adapter<CalendarViewHolder>
{
private final ArrayList<LocalDate> days;
private final OnItemListener onItemListener;
#NonNull
#Override
public CalendarViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.calendar_cell, parent, false);
ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
layoutParams.height = (int) (parent.getHeight() * 0.199999999); //월별 달력
return new CalendarViewHolder(view, onItemListener, days);
}
// 생성된 ViewHolder 에 데이터 바인딩
#Override
public void onBindViewHolder(#NonNull CalendarViewHolder holder, int position)
{
//날짜 변수에 담기
final LocalDate date = days.get(position);
if (date == null)
//날짜가 null인 경우 홀더 날짜를 설정
holder.dayOfMonth.setText("");
else {
//그렇지 않으면 날짜 넣기
holder.dayOfMonth.setText(String.valueOf(date.getDayOfMonth()));
//선택한 날짜 회색으로 표시
if (date.equals(CalendarUtils.selectedDate)) {
holder.parentView.setBackgroundColor(Color.LTGRAY);
}
//주말 색상 지정(토요일: BLUE, 일요일: RED)
if ((position + 1) % 7 == 0) {
holder.dayOfMonth.setTextColor(Color.BLUE);
} else if (position == 0 || position % 7 == 0) {
holder.dayOfMonth.setTextColor(Color.RED);
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
for (int i = 0; CalendarActivity.eventsList.size()>i ; i++) {
Event CalendarDate1 = CalendarActivity.eventsList.get(i);
Date curr = dateFormat.parse(date.toString());
// yyyy-MM-dd
Date d1 = dateFormat.parse(CalendarDate1.startdate);
Date d2 = dateFormat.parse(CalendarDate1.enddate);
int result1 = curr.compareTo(d1); // curr > d1
int result2 = curr.compareTo(d2);
// BLUE
if ((result1 >= 0) && (result2 <= 0))
holder.parentView.setBackgroundColor(Color.parseColor("#83BBF3"));
}
}
catch (ParseException e) {
e.printStackTrace();
}
}
}
// 전체 데이터 개수 return
#Override
public int getItemCount()
{
return days.size();
}
public interface OnItemListener
{
//해당 변수 이름은 현재날짜로 변경됨
void onItemClick(int position, LocalDate date);
}
}
`
I've moved the GetData function to another activity.
Because the code to update the data is in the calendar activity, the data is imported when the calendar is first turned on, but it cannot be modified and deleted.

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

E/AudioRecord: AudioFlinger could not create record track, status: -1

I had this error on my VoiSip Application
E/AudioRecord: AudioFlinger could not create record track, status: -1
E/AudioGroup: cannot initialize audio device
This error occurs after I'm trying to make call to another sip address
Here have 2 java class(WalkieTalkieActivity.java & IncomingCallReceiver.java)
WalkieTalkieActivity.java
public class WalkieTalkieActivity extends Activity implements View.OnTouchListener {
public IncomingCallReceiver callReceiver;
public SipManager mSipManager = null;
public SipProfile mSipProfile = null;
public SipAudioCall call = null;
TextView tv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_walkie_talkie);
ToggleButton pushToTalkButton = (ToggleButton) findViewById(R.id.pushToTalk);
pushToTalkButton.setOnTouchListener(this);
IntentFilter filter = new IntentFilter();
filter.addAction("android.SipDemo.INCOMING_CALL");
callReceiver = new IncomingCallReceiver();
this.registerReceiver(callReceiver, filter);
if (mSipManager == null) {
mSipManager = SipManager.newInstance(this);
}
tv = (TextView)findViewById(R.id.textView);
}
#Override
public void onStart() {
super.onStart();
// When we get back from the preference setting Activity, assume
// settings have changed, and re-login with new auth info.
initializeManager();
}
#Override
public void onDestroy() {
super.onDestroy();
if (call != null) {
call.close();
}
closeLocalProfile();
if (callReceiver != null) {
this.unregisterReceiver(callReceiver);
}
}
public void closeLocalProfile() {
if (mSipManager == null) {
return;
}
try {
if (mSipProfile != null) {
mSipManager.close(mSipProfile.getUriString());
}
} catch (Exception ee) {
Log.d("onDestroy", "Failed to close local profile.", ee);
}
}
public void initializeManager() {
if(mSipManager == null) {
mSipManager = SipManager.newInstance(this);
}
initializeLocalProfile();
}
private void initializeLocalProfile() {
String domain = "mydomain";
String username = "myusername";
String password = "mypassword";
try {
SipProfile.Builder builder = new SipProfile.Builder(username, domain);
builder.setPassword(password);
mSipProfile = builder.build();
if (mSipProfile == null){
Log.e("error cukimai", "null");
}else{
Log.e("error cukimai", "not null");
}
Intent i = new Intent();
i.setAction("android.SipDemo.INCOMING_CALL");
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, Intent.FILL_IN_DATA);
mSipManager.open(mSipProfile, pi, null);
mSipManager.setRegistrationListener(mSipProfile.getUriString(), new SipRegistrationListener() {
public void onRegistering(String localProfileUri) {
updateStatus("Registering with SIP Server...");
Log.e("process","Registering with SIP Server...");
}
public void onRegistrationDone(String localProfileUri, long expiryTime) {
updateStatus("Ready");
Log.e("process","ready");
}
public void onRegistrationFailed(String localProfileUri, int errorCode,
String errorMessage) {
updateStatus("Registration failed. Please check settings.");
Log.e("process","Registration failed. Please check settings.");
}
});
Log.e("process","stop");
} catch (SipException e) {
e.printStackTrace();
Log.e("error cukimai", "cuk cuk");
} catch (ParseException e) {
e.printStackTrace();
Log.e("error cukimai", "cuk");
}
}
public void updateStatus(final String st){
this.runOnUiThread(new Runnable() {
public void run() {
tv.setText(st);
}
});
}
public void updateStatus(SipAudioCall call) {
String useName = call.getPeerProfile().getDisplayName();
if(useName == null) {
useName = call.getPeerProfile().getUserName();
}
updateStatus(useName + "#" + call.getPeerProfile().getSipDomain());
}
public void callAct(View view) {
Toast.makeText(this, "about to make call", Toast.LENGTH_LONG).show();
makeCall();
}
public void makeCall(){
try {
SipAudioCall.Listener listener = new SipAudioCall.Listener() {
// Much of the client's interaction with the SIP Stack will
// happen via listeners. Even making an outgoing call, don't
// forget to set up a listener to set things up once the call is established.
#Override
public void onCallEstablished(SipAudioCall call) {
call.startAudio();
call.setSpeakerMode(true);
call.toggleMute();
updateStatus(call);
}
#Override
public void onCallEnded(SipAudioCall call) {
updateStatus("Ready.");
}
};
call = mSipManager.makeAudioCall(mSipProfile.getUriString(), "sip:destination#domain", listener, 30);
Log.e("make call", "true");
start();
}catch (Exception e){
Log.i("error", "Error when trying to close manager.", e);
if (mSipProfile != null) {
try {
mSipManager.close(mSipProfile.getUriString());
} catch (Exception ee) {
Log.i("error", "Error when trying to close manager.", ee);
ee.printStackTrace();
}
}
if (call != null) {
call.close();
}
}
}
#Override
public boolean onTouch(View view, MotionEvent event) {
if (call == null) {
return false;
} else if (event.getAction() == MotionEvent.ACTION_DOWN && call != null && call.isMuted()) {
call.toggleMute();
} else if (event.getAction() == MotionEvent.ACTION_UP && !call.isMuted()) {
call.toggleMute();
}
return false;
}
final MediaRecorder recorder = new MediaRecorder();
final String path;
/**
* Creates a new audio recording at the given path (relative to root of SD card).
*/
public WalkieTalkieActivity(String path) {
this.path = sanitizePath(path);
}
private String sanitizePath(String path) {
if (!path.startsWith("/")) {
path = "/" + path;
}
if (!path.contains(".")) {
path += ".3gp";
}
return Environment.getExternalStorageDirectory().getAbsolutePath() + path;
}
/**
* Starts a new recording.
*/
public void start() throws IOException {
String state = android.os.Environment.getExternalStorageState();
if(!state.equals(android.os.Environment.MEDIA_MOUNTED)) {
throw new IOException("SD Card is not mounted. It is " + state + ".");
}
// make sure the directory we plan to store the recording in exists
File directory = new File(path).getParentFile();
if (!directory.exists() && !directory.mkdirs()) {
throw new IOException("Path to file could not be created.");
}
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(path);
recorder.prepare();
recorder.start();
}
/**
* Stops a recording that has been previously started.
*/
public void stop() throws IOException {
recorder.stop();
recorder.release();
}
}
IncomingCallReceiver.java
public class IncomingCallReceiver extends BroadcastReceiver {
/**
* Processes the incoming call, answers it, and hands it over to the
* WalkieTalkieActivity.
* #param context The context under which the receiver is running.
* #param intent The intent being received.
*/
#Override
public void onReceive(Context context, Intent intent) {
SipAudioCall incomingCall = null;
try {
SipAudioCall.Listener listener = new SipAudioCall.Listener() {
#Override
public void onRinging(SipAudioCall call, SipProfile caller) {
try {
call.answerCall(30);
} catch (Exception e) {
e.printStackTrace();
}
}
};
WalkieTalkieActivity wtActivity = (WalkieTalkieActivity) context;
incomingCall = wtActivity.mSipManager.takeAudioCall(intent, listener);
incomingCall.answerCall(30);
incomingCall.startAudio();
incomingCall.setSpeakerMode(true);
if(incomingCall.isMuted()) {
incomingCall.toggleMute();
}
wtActivity.call = incomingCall;
wtActivity.updateStatus(incomingCall);
} catch (Exception e) {
if (incomingCall != null) {
incomingCall.close();
}
}
}
}
I'm really new on Sip and Voip Implementing in Android Studio. I got this code from google source code.
I believe this error occurs because of the use of hardware (audio). However I have been searching on google for almost 1 week and not giving results. Can someone help me?
I had same problem but when i changed targetSdkVersion to 12 in build.gradel its fixed.
and this answer helped me to fixed problem .
You must choose the BufferSize when you want to record or call in app. For example:
int bufferSize = AudioRecord.getMinBufferSize(rate, channelConfig, audioFormat);
if (bufferSize > 0 && bufferSize <= 256){
bufferSize = 256;
}else if (bufferSize > 256 && bufferSize <= 512){
bufferSize = 512;
}else if (bufferSize > 512 && bufferSize <= 1024){
bufferSize = 1024;
}else if (bufferSize > 1024 && bufferSize <= 2048){
bufferSize = 2048;
}else if (bufferSize > 2048 && bufferSize <= 4096){
bufferSize = 4096;
}else if (bufferSize > 4096 && bufferSize <= 8192){
bufferSize = 8192;
}else if (bufferSize > 8192 && bufferSize <= 16384){
bufferSize = 16384;
}else{
bufferSize = AudioRecord.getMinBufferSize(rate, channelConfig, audioFormat);
}

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

Categories

Resources