I have just created an Android app for delivery boy ,In that admin can assign a duty to him through server.
The problem is that i want a functionality in which app can automatically sends the latitude and longitude to the server every 5 minutes of interval, I had used job scheduler but it is only works in my older phone which is Android Lollipop, it is not working in Android Nougat.
MyService.java
package com.example.dell.firebase;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import com.firebase.jobdispatcher.JobParameters;
import com.firebase.jobdispatcher.JobService;
/**
* Created by DELL on 3/20/2019.
*/
public class MyService extends JobService{
BackgroundTask ba;
#Override
public boolean onStartJob(final JobParameters job) {
ba=new BackgroundTask(){
#Override
protected void onPostExecute(String s) {
Toast.makeText(getApplicationContext(),"hello all "+s,Toast.LENGTH_SHORT).show();
Log.d("dd","hg");
jobFinished(job,false);
}
};
ba.execute();
return true;
}
#Override
public boolean onStopJob(JobParameters job) {
return true;
}
public static class BackgroundTask extends AsyncTask<Void,Void,String>
{
#Override
protected String doInBackground(Void... voids) {
return "hello from background";
}
}
}
My Xml code
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.dell.firebase.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="150dp"
android:onClick="startjob"
android:text="start" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:onClick="stopjob"
android:text="stop" />
</LinearLayout>
</android.support.constraint.ConstraintLayout>
MainActivity.java
package com.example.dell.firebase;
import android.annotation.SuppressLint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.firebase.jobdispatcher.Constraint;
import com.firebase.jobdispatcher.FirebaseJobDispatcher;
import com.firebase.jobdispatcher.GooglePlayDriver;
import com.firebase.jobdispatcher.Job;
import com.firebase.jobdispatcher.Lifetime;
import com.firebase.jobdispatcher.RetryStrategy;
import com.firebase.jobdispatcher.Trigger;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
private static final String jobtag="Mytag";
private FirebaseJobDispatcher jobDispatcher;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
jobDispatcher=new FirebaseJobDispatcher(new GooglePlayDriver(this));
}
public void startjob(View view) {
Job job=jobDispatcher.newJobBuilder()
.setService(MyService.class)
.setLifetime(Lifetime.FOREVER)
.setRecurring(true)
.setTag(jobtag)
.setTrigger(Trigger.executionWindow(10,15))
.setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL)
.setReplaceCurrent(false)
.setConstraints(Constraint.ON_ANY_NETWORK)
.build();
jobDispatcher.mustSchedule(job);
Toast.makeText(this,"job Scheduled",Toast.LENGTH_SHORT).show();
}
public void stopjob(View view) {
jobDispatcher.cancelAll();
Toast.makeText(this,"job Canceled",Toast.LENGTH_SHORT).show();
}
}
Related
I tried other answers but nothing worked. for some reason RecyclerView only displaying one item. I tried changing layout height to wrap content but it didn't worked, still displaying only one item. I'm passing about 20 items.
I have to type more otherwise stackoverflow won't let me post this question. because it mostly code
feed_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/txtStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/txtTransaction"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/txtGeneral"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button btnget;
RecyclerView recycler;
private Session session;
private TextView textViewResult;
ArrayList<Feed> feed ;
private feedadapter feedadap;
String token ="Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJ ";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recycler = findViewById(R.id.recyclerView);
recycler.setLayoutManager(new LinearLayoutManager(this));
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https:url/")
.addConverterFactory(GsonConverterFactory.create())
.build();
JsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);
Call<Feed> call = jsonPlaceHolderApi.getposts( token);
call.enqueue(new Callback<Feed>() {
#Override
public void onResponse(Call<Feed> call, Response<Feed> response) {
feed = new ArrayList<>(Arrays.asList(response.body()));
feedadap = new feedadapter(MainActivity.this,feed);
recycler.setAdapter(feedadap);
Log.d("msgcontent",feed.toString());
}
#Override
public void onFailure(Call<Feed> call, Throwable t) {
}
});
}
#Override
public void onClick(View view) {
}
}
check getItemCount() in your FeedAdapter.
it's must look like this:
#Override
public int getItemCount() {
return feed.size();
}
I'm following a retrofit tutorial https://futurestud.io/tutorials/retrofit-getting-started-and-android-client
The app compiles and runs but doesn't allow you to scroll beyond the first page. Any idea what I'm missing? Does this tutorial even have you show all the repos?
https://github.com/morenoh149/HarryLearnsAndroid/tree/master/HttpDemo
package com.harrymoreno.httpdemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import com.harrymoreno.httpdemo.GitHubRepoAdapter;
public class MainActivity extends AppCompatActivity {
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.pagination_list);
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
GithubClient client = retrofit.create(GithubClient.class);
Call<List<GithubRepo>> call = client.reposForUser("morenoh149");
call.enqueue(new Callback<List<GithubRepo>>() {
#Override
public void onResponse(Call<List<GithubRepo>> call, Response<List<GithubRepo>> response) {
List<GithubRepo> repos = response.body();
listView.setAdapter(new GitHubRepoAdapter(MainActivity.this, repos));
}
#Override
public void onFailure(Call<List<GithubRepo>> call, Throwable t) {
Toast.makeText(MainActivity.this, "error :(", Toast.LENGTH_SHORT).show();
}
});
}
}
and activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:id="#+id/pagination_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
tools:layout_editor_absoluteX="0dp" />
</RelativeLayout>
use scrollview then listview in xml file
In my android app I have an image slider using viewpager,which changes images every 2.5 seconds in the main activity,it works fine when I open the app,but the problem is when I jump to another Activity from the MainActivity and come back it,starts to move the images in the slides very fast,as much as I jump to another activity the sliding become more faster.please help.
This is where I have included my 3 slider images
slidelist.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:id="#+id/image1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:adjustViewBounds="true"
android:layout_gravity="center"
android:src="#drawable/slidetwo"
android:scaleType="centerCrop"/>
<ImageView
android:id="#+id/image2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:adjustViewBounds="true"
android:layout_gravity="center"
android:src="#drawable/slideone"
android:scaleType="centerCrop"/>
<ImageView
android:id="#+id/image3"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:adjustViewBounds="true"
android:layout_gravity="center"
android:src="#drawable/slidethree"
android:scaleType="centerCrop"/>
</FrameLayout>
This the slider layout in content main.xml(included in activity)
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="250dp"
android:layout_below="#+id/linearone">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true" />
<me.relex.circleindicator.CircleIndicator
android:id="#+id/indicator"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
The following is the adpater class
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.example.rimapps.icar_iisr_turmeric.R;
import java.util.ArrayList;
public class SlideAdapter extends PagerAdapter {
private ArrayList<Integer> images;
private LayoutInflater inflater;
private Context context;
public SlideAdapter(Context context, ArrayList<Integer> images) {
this.context = context;
this.images=images;
inflater = LayoutInflater.from(context);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return images.size();
}
#Override
public Object instantiateItem(ViewGroup view, int position) {
View myImageLayout = inflater.inflate(R.layout.slidelist, view, false);
ImageView myImage1 = (ImageView) myImageLayout.findViewById(R.id.image1);
ImageView myImage2 = (ImageView) myImageLayout.findViewById(R.id.image2);
ImageView myImage3 = (ImageView) myImageLayout.findViewById(R.id.image3);
myImage1.setImageResource(images.get(position));
myImage2.setImageResource(images.get(position));
myImage3.setImageResource(images.get(position));
view.addView(myImageLayout, 0);
return myImageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
}
This is my MainActivity class and here I have defined the timer for the slider
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.internal.NavigationMenuItemView;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import com.example.rimapps.icar_iisr_turmeric.R;
import com.example.rimapps.icar_iisr_turmeric.control.ButtonAdapter;
import com.example.rimapps.icar_iisr_turmeric.control.SlideAdapter;
import com.example.rimapps.icar_iisr_turmeric.model.ContentsDep;
import com.example.rimapps.icar_iisr_turmeric.utils.LocaleHelper;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import me.relex.circleindicator.CircleIndicator;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
CircleIndicator indicator;
int period=2500, delay = 2500;
private static ViewPager mPager;
private static int currentPage = 0;
private static final Integer[] slide = {R.drawable.slideone, R.drawable.slidetwo, R.drawable.slidethree};
private ArrayList<Integer> slidearray = new ArrayList<Integer>();
Timer swipeTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
//Image slider function//
private void init() {
for (int i = 0; i < slide.length; i++)
slidearray.add(slide[i]);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(new SlideAdapter(MainActivity.this, slidearray));
CircleIndicator indicator = (CircleIndicator) findViewById(R.id.indicator);
indicator.setViewPager(mPager);
// Auto start of viewpager
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == slide.length) {
currentPage = 0;
}
mPager.setCurrentItem(currentPage++, true);
}
};
swipeTimer =new Timer();
swipeTimer.schedule(new
TimerTask() {
#Override
public void run () {
Log.d("hjgv","yughi");
handler.post(Update);
}
},delay,period);
}
#Override
protected void onStop() {
super.onStop();
// swipeTimer.cancel();
delay=0;
period=0;
}
#Override
protected void onRestart() {
super.onRestart();
delay=2500;
period=2500;
}
}
The problem is in your Timer.
when you go another fragment or activity then back to that fragment you must have to cancel your timer ondestroyview because when you back to fragment your oncreateview is call again so timer are initialise and then speed is multiple by 2 time.this happens everytime.
This code in kotlin.
override fun onDestroyView() {
if(swipeTimer != null) {
swipeTimer.cancel()
}
super.onDestroyView()
}
Hope this help you
Just call cancel the instance of Timer in your ondestryView() method
#Override
public void onDestroyView() {
super.onDestroyView();
if(swipeTimer != null) {
swipeTimer.cancel();
}
}
I integrated Tap Research sdk on my Android app, but application getting force stop.
Any idea why this might be happening?
This is my code tapresearchactivity.java
import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.tapr.sdk.TapResearch;
import com.tapr.sdk.TapResearchOnRewardListener;
class MyApp extends Application {
final private String YOUR_API_TOKEN = "fa7dbeeacebe7ae3e0b24e8dccaa6acb";
public class onCreate{} {
super.onCreate();
TapResearch.configure(YOUR_API_TOKEN, this);
}
}
public class TapresearchActivity extends Activity {
private Button show_button;
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_tapresearch);
/** Set up button to show an ad when clicked */
show_button = (Button) findViewById(R.id.showbutton);
if (TapResearch.getInstance().isSurveyAvailable()) {
show_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TapResearch.getInstance().showSurvey();
}
});
}
}
}
And this is my xml layout file here activity_tapreserch.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".TapresearchActivity">
<Button
android:layout_width="298dp"
android:layout_height="68dp"
android:enabled="false"
android:id="#+id/showbutton"
android:background="#drawable/button_blue"
android:layout_alignParentBottom="true"
android:layout_marginBottom="10dp"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
I am trying to implement a progress bar, that appears when loading the page and disappears when the page is finished loading. I have added on finish parameter but it seems that it is not being recognized.
Code
package com.test;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;
import com.parse.ParseInstallation;
import com.parse.ParsePush;
import com.parse.ParseQuery;
import com.parse.PushService;
public class MainActivity extends Activity implements OnClickListener {
private Button push;
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(getApplicationContext(), "onReceive invoked!", Toast.LENGTH_LONG).show();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setProgressBarIndeterminateVisibility(true);
setContentView(R.layout.activity_main);
PushService.setDefaultPushCallback(this, MainActivity.class);
WebView webView = (WebView) findViewById(R.id.webView1);;
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.teqez.com/xx/ ");
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setBuiltInZoomControls(false);
push = (Button)findViewById(R.id.senPushB);
push.setOnClickListener(this);
}
private class HelloWebViewClient extends WebViewClient{
#Override
public boolean shouldOverrideUrlLoading(WebView webview, String url){
webview.loadUrl(url);
setProgressBarIndeterminateVisibility(true);
return true;
}
#Override
public void onPageFinished(WebView webview, String url){
super.onPageFinished(webview, url);
setProgressBarIndeterminateVisibility(false);
}
}
private class Callback extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return (true);
}
}
#Override
public void onBackPressed()
{
WebView webView = (WebView) findViewById(R.id.webView1);
if(webView.canGoBack()){
webView.goBack();
}else{
super.onBackPressed();
}
}
#Override
public void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver);
}
#Override
public void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, new IntentFilter(MyCustomReceiver.intentAction));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onClick(View v) {
JSONObject obj;
try {
obj = new JSONObject();
obj.put("alert", "hello!");
obj.put("action", MyCustomReceiver.intentAction);
obj.put("customdata","My message");
ParsePush push = new ParsePush();
ParseQuery query = ParseInstallation.getQuery();
// Push the notification to Android users
query.whereEqualTo("deviceType", "android");
push.setQuery(query);
push.setData(obj);
push.sendInBackground();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Button
android:id="#+id/senPushB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:background="#drawable/ic_launcher"
android:text="Check For Updates" />
<WebView
android:id="#+id/webView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:clickable="true"
android:focusable="true" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</RelativeLayout>
You do not invoke your custom private class
Change
webView.setWebViewClient(new WebViewClient());
to
webView.setWebViewClient(new HelloWebViewClient());