This question already has answers here:
Why a non-static inner-class cannot have static members (fields and methods)? [duplicate]
(3 answers)
RecyclerView: Inner classes cannot have static declaration
(2 answers)
Closed 4 years ago.
I have posted the HandlerThread class where I got an error on the following line:
private final static String TAG_LOG = MainAct.TAG_LOG + "->" + RoomPersistentDBHandlerThread.class.getSimpleName();
The error was inner class cant have inner static memedeclartion.
Can any of you explain to me why for the aforementioned line of code, I could not declare static variable inside the
inner class, despite in the immediate following line, the static variable has no errors.
thanks
code:
class MainAct {
public void buildPersistentDB() {
}
private class RoomPersistentDBHandlerThread extends HandlerThread implements Handler.Callback {
private final static String TAG_LOG = MainAct.TAG_LOG + "->" + RoomPersistentDBHandlerThread.class.getSimpleName();
private final static String THROW_ON_LOOPER_NOT_INITIALIZED = "LOOPER_NOT_INITIALIZED";
private WeakReference<Context> mWeakReferenceToActMain;
private Handler mHandler = null;
private final static String markerAstrisks = "++++++++++++++++++++++++ ";
public RoomPersistentDBHandlerThread(String name, Context context) {
super(name);
Log.w(TAG_LOG, "RoomPersistentDBHandlerThread constructor is called.");
this.mWeakReferenceToActMain = new WeakReference<>(context);
}
#Override
protected void onLooperPrepared() {
super.onLooperPrepared();
Log.w(TAG_LOG, "onLooperPrepared is called.");
Log.v(TAG_LOG, markerAstrisks + " [getLooper: " + this.getLooper() + "] " + markerAstrisks);
try {
this.mHandler = Optionals.toOptional(this.getLooper())
.map(looper -> new Handler(looper, this))
.orElseThrow(() -> new NullPointerException(THROW_ON_LOOPER_NOT_INITIALIZED));
} catch (Throwable throwable) {
throwable.printStackTrace();
}//eof catch
}//eof onLooperPrepared
public void enqueueMessage(int what) {
Log.w(TAG_LOG, "enqueueMessage is called for what = " + what);
this.mHandler.sendEmptyMessage(what);
}
#Override
public boolean handleMessage(Message msg) {
Log.w(TAG_LOG, "handleMessage is called for msg.what = " + msg.what);
switch(msg.what) {
case WHAT_MSG_INIT_PERSISTENT_DATABASE:
mWeakReferenceToActMain.get()
break;
}
return true;
}
}//eof-RoomPersistentDBHandlerThread
}
Related
I'm trying to use RETROFIT to get an inform about COVID-19 data. And I want to show the latest data, so I tried
content1 = covid_post_data.getPositive() + "\n";
content2 = covid_post_data.getDeath() + "\n";
content3 = " (+" + covid_post_data.getPositiveIncrease() + ")\n";
content4 = " (+" + covid_post_data.getDeathIncrease() + ")\n";
content5 = " Updated : " + covid_post_data.getDate() + "\n";
textViewResult.setText(content1);
textViewResult2.setText(content2);
textViewResult3.setText(content3);
textViewResult4.setText(content4);
textViewResult5.setText(content5);
But it is not working.it didn't show any data. how can i show the latest data in JSON file with using retrofit? below is my whole code of main activity
1.MainActivity
public class COVIDActivity extends AppCompatActivity {
private TextView textViewResult;
private TextView textViewResult2;
private TextView textViewResult3;
private TextView textViewResult4;
private TextView textViewResult5;
private static final String TAG = "COVIDActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.covid_menu);
//How go_back_button works
ImageButton bo_back_Button = (ImageButton) findViewById(R.id.covid_to_main);
bo_back_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent move_main_covid = new Intent(COVIDActivity.this,MainActivity.class);
startActivity(move_main_covid);
}
});
textViewResult = findViewById(R.id.text_view_result_positive);
textViewResult2 = findViewById(R.id.text_view_result_death);
textViewResult3 = findViewById(R.id.text_view_result_positive_increase);
textViewResult4 = findViewById(R.id.text_view_result_death_increase);
textViewResult5 = findViewById(R.id.today_date);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://covidtracking.com/api/v1/")
.addConverterFactory(GsonConverterFactory.create())
.build();
JsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);
Call<List<COVID_Post_Data>> call = jsonPlaceHolderApi.get_covid_post();
call.enqueue(new Callback<List<COVID_Post_Data>>() {
#Override
public void onResponse(Call<List<COVID_Post_Data>> call, Response<List<COVID_Post_Data>> response) {
if (!response.isSuccessful()) {
textViewResult.setText(("Code: " + response.code()));
return;
}
List<COVID_Post_Data> posts = response.body();
//Give message if fail, TAG is COVIDActivity so that it will show log in this activity
if(posts == null) {
Log.w(TAG,"Did not receive any valid response body");
return;
}
for (COVID_Post_Data covid_post_data : posts) {
String content1,content2,content3,content4,content5 = "";
content1 = covid_post_data.getPositive() + "\n";
content2 = covid_post_data.getDeath() + "\n";
content3 = " (+" + covid_post_data.getPositiveIncrease() + ")\n";
content4 = " (+" + covid_post_data.getDeathIncrease() + ")\n";
content5 = " Updated : " + covid_post_data.getDate() + "\n";
textViewResult.append(content1);
textViewResult2.append(content2);
textViewResult3.append(content3);
textViewResult4.append(content4);
textViewResult5.append(content5);
}
}
2.get JSON file
public interface JsonPlaceHolderApi {
//get data from json about US infection
#GET("us/daily.json")
Call<List<COVID_Post_Data>> get_covid_post();
//get data from json about states infection
#GET("states/daily.json")
Call<List<COVID_Post_Data>> get_covid_post_state();
}
3.getter function
public class COVID_Post_Data {
private String dataChecked;
private int positiveIncrease;
private int negativeIncrease;
private int deathIncrease;
private String state;
private int positive;
private int death;
private int date;
//if the variable is matched with name in json file no need to put #SerializedName here
public String getDataChecked() {
return dataChecked;
}
public int getPositiveIncrease() {
return positiveIncrease;
}
public int getNegativeIncrease() {
return negativeIncrease;
}
public int getDeathIncrease() {
return deathIncrease;
}
public String getState() {
return state;
}
public int getPositive() {
return positive;
}
public int getDeath() { return death; }
public int getDate() {
return date;
}
}
I am learnign how to handle and to use functional programming in Android. So I developed the below code. I would like to handle the HandlerThread as observable, but when I try to call .start() from
.map() operator I receive the following error:
no instances of type variable(s) R exists so that void conforms to R
please let me know why I am getting this error and how to solve it.
code:
public Single<HandlerThread> getObsInitializedHandlerThread() {
this.mMyHandlerThread = new MyHandlerThread(NAME_MY_HANDLER_THREAD);
return Single.just(this.mMyHandlerThread);
}
#Override
protected void onResume() {
super.onResume();
String TAG_LOG = ActMain.TAG_LOG + "." + "onResume()";
Log.v(TAG_LOG, ":");
this.getObsInitializedHandlerThread()
.map(mMyHandlerThread -> mMyHandlerThread.start());
}
private class MyHandlerThread extends HandlerThread {
public MyHandlerThread(String name) {
super(name);
String TAG_LOG = ActMain.class.getSimpleName() + "." + "MyHandlerThread() Constructor";
Log.v(TAG_LOG, ":");
}
#Override
protected void onLooperPrepared() {
super.onLooperPrepared();
String TAG_LOG = ActMain.class.getSimpleName() + "." + onLoopPrepared()";
Log.v(TAG_LOG, ":");
}
}
In map you allways need to return a value (T) you cant return a void so can you trye
this.getObsInitializedHandlerThread()
.map(mMyHandlerThread ->{
mMyHandlerThread.start();
return mMyHandlerThread;
});
I have modified ActivityTestRule to retry executing failed test cases. I need to restart the activity and re-run the execution whenever there is a test failure. I have tried calling mActivity.finish() but current activity is not finishing and not restarting. But the tests are restarted. I have followed this method from here
public class MyActivityTestRule<T extends Activity> extends ActivityTestRule<T> {
private final Class<T> mActivityClass;
private T mActivity;
private static final String TAG = "ActivityInstrumentationRule";
private boolean mInitialTouchMode = false;
private Instrumentation mInstrumentation;
public MyActivityTestRule(Class<T> activityClass, boolean initialTouchMode, boolean launchActivity) {
super(activityClass, initialTouchMode, launchActivity);
mActivityClass = activityClass;
mInitialTouchMode = initialTouchMode;
mInstrumentation = InstrumentationRegistry.getInstrumentation();
}
#Override
public Statement apply(Statement base, Description description) {
final String testClassName = description.getClassName();
final String testMethodName = description.getMethodName();
final Context context = InstrumentationRegistry.getTargetContext();
/* android.support.test.espresso.Espresso.setFailureHandler(new FailureHandler() {
#Override public void handle(Throwable throwable, Matcher<View> matcher) {
if(AutomationTestCase.mEnableScreenshotOnFailure)
SpoonScreenshotOnFailure.perform("espresso_assertion_failed", testClassName, testMethodName);
new DefaultFailureHandler(context).handle(throwable, matcher);
}
});*/
// return super.apply(base, description);
return statement(base, description);
}
private Statement statement(final Statement base, final Description description) {
return new Statement() {
#Override
public void evaluate() throws Throwable {
Throwable caughtThrowable = null;
//retry logic
for (int i = 0; i < 3; i++) {
try {
launchAppActivity(getActivityIntent());
base.evaluate();
return;
} catch (Throwable t) {
caughtThrowable = t;
System.err.println(description.getDisplayName() + ": run " + (i+1) + " failed");
finishActivity();
} finally {
finishActivity();
}
}
System.err.println(description.getDisplayName() + ": giving up after " + 3 + " failures");
throw caughtThrowable;
}
};
}
void finishActivity() {
if (mActivity != null) {
mActivity.finish();
mActivity = null;
}
}
public T launchAppActivity(#Nullable Intent startIntent) {
// set initial touch mode
mInstrumentation.setInTouchMode(mInitialTouchMode);
final String targetPackage = mInstrumentation.getTargetContext().getPackageName();
// inject custom intent, if provided
if (null == startIntent) {
startIntent = getActivityIntent();
if (null == startIntent) {
Log.w(TAG, "getActivityIntent() returned null using default: " +
"Intent(Intent.ACTION_MAIN)");
startIntent = new Intent(Intent.ACTION_MAIN);
}
}
startIntent.setClassName(targetPackage, mActivityClass.getName());
startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Log.d(TAG, String.format("Launching activity %s",
mActivityClass.getName()));
beforeActivityLaunched();
// The following cast is correct because the activity we're creating is of the same type as
// the one passed in
mActivity = mActivityClass.cast(mInstrumentation.startActivitySync(startIntent));
mInstrumentation.waitForIdleSync();
afterActivityLaunched();
return mActivity;
}}
If your test ended up in a different activity than what the ActivityTestRule was initialized as, you'll have to close all the activities in the backstack. This example may help:
https://gist.github.com/patrickhammond/19e584b90d7aae20f8f4
I am trying to write a simple app for Google TV which generates a random number from 1-10 then randomly selects a channel (501-510) and loads it.
I have tried the official google documentation but the official sample project doesnt compile. I have also read Is the GTV Channel Listing/Change API/Sample is broken on LG G2? and tried to adapt this into the google version however the app crashes on loading.
Im sure this must be a simple fix. I do not need to get information about the channel or search for them using the tutorial at https://developers.google.com/tv/android/docs/gtv_provider.
Any help greatly appreciated.
The access to the providers have changed if you use the code below things should improve.
Permissions:
<uses-permission android:name="com.google.android.tv.permission.READ_CHANNELS"/>
<uses-permission android:name="com.google.android.tv.mediadevices.permission.READ_STREAMS"/>
code:
public abstract class ChannelList {
private static ChannelList mCL=null;
public abstract String getPROVIDER_URI();
public abstract String getCALL_SIGN_COLUMN();
public abstract String getURI_COLUMN();
public abstract String getNUMBER_COLUMN();
public abstract String getNAME_COLUMN();
public static ChannelList getChannelList() {
if (mCL != null)
return mCL;
int mGtvLibraryVersion = 0;
try {
Class<?> cl = Class.forName("com.google.android.tv.Version");
mGtvLibraryVersion = cl.getField("GTV_SDK_INT").getInt(null);
} catch (Exception ex) {}
Log.d("Resolution Test", "Version " + mGtvLibraryVersion);
mCL= mGtvLibraryVersion > 0 ? new Version3ChannelList(): new Version2ChannelList();
return mCL;
}
/**
* Use the getChannelList factory to obtain an instance of a subclass of
* ChannelList
*/
private ChannelList() {
}
#Override
public String toString() {
return "SDK Provider: " + getPROVIDER_URI() + "\n" +
"Columns: " + getCALL_SIGN_COLUMN() + " " + getURI_COLUMN() + " " + getNUMBER_COLUMN() + " "
+ getNAME_COLUMN();
}
public static final class Version2ChannelList extends ChannelList {
#Override
public String getPROVIDER_URI() {
return "content://com.google.android.tv.provider/channel_listing";
}
#Override
public String getCALL_SIGN_COLUMN() {
return "callsign";
}
#Override
public String getURI_COLUMN() {
return "channel_uri";
}
#Override
public String getNUMBER_COLUMN() {
return "channel_number";
}
#Override
public String getNAME_COLUMN() {
return "channel_name";
}
}
public static final class Version3ChannelList extends ChannelList {
#Override
public String getPROVIDER_URI() {
return "content://com.google.tv.mediadevicesapp.MediaDevicesProvider/channel_list";
}
#Override
public String getCALL_SIGN_COLUMN() {
return "subName";
}
#Override
public String getURI_COLUMN() {
return "url";
}
#Override
public String getNUMBER_COLUMN() {
return "channelNumber";
}
#Override
public String getNAME_COLUMN() {
return "name";
}
}
While investigating memory issues in our application, it turns out that if the application Activity is a MapActivity, the first instance of it won't be finalized. Leading to other memory leak such as the view passed to setContentView.
Does anyone notice that before?
Here is the testing code showing that "MainActivity : 1" is not finalized whereas it is if MainActivity inherits from Activity.
To test, one needs to change device or emulator orientation many times.
import com.google.android.maps.MapActivity;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends MapActivity {
private static final String defaultTag = "MA";
private static final boolean isDebugModeActivate = true;
private static final boolean isClassTagDisplayed = false;
private static final boolean isWebModeActivate = false;
static public void d(Object thiso, String message)
{
String tag = defaultTag + (isClassTagDisplayed == true ? "_" + thiso.getClass().getSimpleName() : "");
message = (isClassTagDisplayed == false ? thiso.getClass().getSimpleName() + " : " : "") + message;
Log.d(tag, message);
}
public MainActivity()
{
counter++;
uid++;
id = uid;
d(this, id + " tst constructor (" + counter + ")");
}
private static int counter = 0;
private static int uid = 0;
private final int id;
protected void finalize() throws Throwable
{
counter--;
d(this, id + " tst finalize (" +counter + ") ");
super.finalize();
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
protected boolean isRouteDisplayed()
{
return false;
}
}
Thank you,
David
Perhaps you should exchange notes with NickT here