Styling OssLicensesMenuActivity - android

I am using a Google library called play-services-plugins to include Open Source Notices on my app.
I could implement it with no problem, but I have no idea how I can style the activity that displays the license.
In my code, I start the activity by calling startActivity(Intent(this, OssLicensesMenuActivity::class.java))
Since OssLicensesMenuActivity is an Activity class, I manage to style like this:
styles.xml:
<style name="LicensesTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">#color/colorPrimaryDark</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
AndroidManifest.xml:
<activity
android:name="com.google.android.gms.oss.licenses.OssLicensesMenuActivity"
android:theme="#style/LicensesTheme" />
This works like a charm, but this activity just displays all the libraries I'm using.
There is a second activity that displays the licence and that's the one I can't figure out how to style. The problem I'm facing is that the code from OssLicensesMenuActivity is obfuscated and I can't find the name and package of the activity class I want to style.
Anyone knows how I can solve this problem?
Just to it's easier to check, the obfuscated code from OssLicensesMenuActivity is the following:
package com.google.android.gms.oss.licenses;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.content.res.Resources.NotFoundException;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.appcompat.app.AppCompatActivity;
import androidx.loader.app.LoaderManager.LoaderCallbacks;
import androidx.loader.content.Loader;
import com.google.android.gms.common.annotation.KeepForSdk;
import com.google.android.gms.internal.oss_licenses.zzc;
import com.google.android.gms.oss.licenses.R.id;
import com.google.android.gms.oss.licenses.R.layout;
import com.google.android.gms.tasks.Task;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public final class OssLicensesMenuActivity extends AppCompatActivity implements LoaderCallbacks<List<zzc>> {
private static String zzx;
private ListView zzy;
private ArrayAdapter<zzc> zzz;
private boolean zzaa;
private zze zzp;
private Task<String> zzab;
private com.google.android.gms.oss.licenses.zzc zzo;
public OssLicensesMenuActivity() {
}
#KeepForSdk
protected final void onCreate(#Nullable Bundle var1) {
super.onCreate(var1);
this.zzo = com.google.android.gms.oss.licenses.zzc.zza(this);
this.zzaa = fileExistsAndNotEmpty(this, "third_party_licenses") && fileExistsAndNotEmpty(this, "third_party_license_metadata");
Intent var3;
if (zzx == null && (var3 = this.getIntent()).hasExtra("title")) {
zzx = var3.getStringExtra("title");
Log.w("OssLicensesMenuActivity", "The intent based title is deprecated. Use OssLicensesMenuActivity.setActivityTitle(title) instead.");
}
if (zzx != null) {
this.setTitle(zzx);
}
if (this.getSupportActionBar() != null) {
this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
if (this.zzaa) {
zzh var10001 = com.google.android.gms.oss.licenses.zzc.zza(this).zzb();
String var4 = this.getPackageName();
zzh var2 = var10001;
this.zzab = var10001.doRead(new zzk(var2, var4));
this.getSupportLoaderManager().initLoader(54321, (Bundle)null, this);
this.zzab.addOnCompleteListener(new zzp(this));
} else {
this.setContentView(layout.license_menu_activity_no_licenses);
}
}
public static void setActivityTitle(#NonNull String var0) {
zzx = var0;
}
#VisibleForTesting(
otherwise = 2
)
#KeepForSdk
static boolean fileExistsAndNotEmpty(#NonNull Context var0, #NonNull String var1) {
InputStream var2 = null;
try {
Resources var3;
String var4 = (var3 = var0.getResources()).getResourcePackageName(id.license_list);
boolean var5 = (var2 = var3.openRawResource(var3.getIdentifier(var1, "raw", var4))).available() > 0;
return var5;
} catch (IOException | NotFoundException var13) {
} finally {
if (var2 != null) {
try {
var2.close();
} catch (IOException var12) {
}
}
}
return false;
}
#KeepForSdk
public final boolean onOptionsItemSelected(MenuItem var1) {
if (var1.getItemId() == 16908332) {
this.finish();
return true;
} else {
return super.onOptionsItemSelected(var1);
}
}
#KeepForSdk
public final void onDestroy() {
this.getSupportLoaderManager().destroyLoader(54321);
super.onDestroy();
}
#KeepForSdk
public final Loader<List<zzc>> onCreateLoader(int var1, Bundle var2) {
return this.zzaa ? new zzo(this, com.google.android.gms.oss.licenses.zzc.zza(this)) : null;
}
#KeepForSdk
public final void onLoadFinished(Loader<List<zzc>> var1, List<zzc> var2) {
this.zzz.clear();
this.zzz.addAll(var2);
this.zzz.notifyDataSetChanged();
}
#KeepForSdk
public final void onLoaderReset(Loader<List<zzc>> var1) {
this.zzz.clear();
this.zzz.notifyDataSetChanged();
}
private class zza extends ArrayAdapter<zzc> {
zza(Context var2) {
OssLicensesMenuActivity.this.zzo;
int var10002 = com.google.android.gms.oss.licenses.zzc.zza(OssLicensesMenuActivity.this.zzp);
OssLicensesMenuActivity.this.zzo;
super(var2, var10002, com.google.android.gms.oss.licenses.zzc.zzb(OssLicensesMenuActivity.this.zzp), new ArrayList());
}
public final View getView(int var1, View var2, ViewGroup var3) {
if (var2 == null) {
OssLicensesMenuActivity.this.zzo;
LayoutInflater var10000 = OssLicensesMenuActivity.this.getLayoutInflater();
zze var6 = OssLicensesMenuActivity.this.zzp;
LayoutInflater var4 = var10000;
XmlResourceParser var7 = var6.zzg.getXml(com.google.android.gms.oss.licenses.zzc.zza(var6));
var2 = var4.inflate(var7, var3, false);
}
OssLicensesMenuActivity.this.zzo;
((TextView)var2.findViewById(com.google.android.gms.oss.licenses.zzc.zzb(OssLicensesMenuActivity.this.zzp))).setText(((zzc)this.getItem(var1)).toString());
return var2;
}
}
}

Just do the same for "OssLicensesActivity" as you did for "OssLicensesMenuActivity" in the Manifest:
<activity android:name="com.google.android.gms.oss.licenses.OssLicensesActivity"
android:theme="#style/LicensesTheme" />
This should style the "second activity that displays the licence".

Related

"SinchClient not started" The main problem in android studio

I am facing this problem for the last two weeks. Can you help me why this problem occurs?
Error occur at this line allClient.callPhoneNumber("+16315192247");
Please check it. Every time it crashes.
package com.eureka.voicecallinapk;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.sinch.android.rtc.PushPair;
import com.sinch.android.rtc.Sinch;
import com.sinch.android.rtc.SinchClient;
import com.sinch.android.rtc.SinchError;
import com.sinch.android.rtc.calling.Call;
import com.sinch.android.rtc.calling.CallClient;
import com.sinch.android.rtc.calling.CallClientListener;
import com.sinch.android.rtc.calling.CallListener;
import java.util.List;
public class MainActivity extends AppCompatActivity {
public static final String APP_KEY = "b7258284-f0dnd-4734-afec-210d387d****";
//i do it for security because i am posting here
public static final String APP_SECRET = "k76tOLgz+kSdKL7ULYsH**==";
public static final String ENVIRONMENT = "clientapi.sinch.com";
public Call call;
private TextView callState;
public SinchClient sinchClient;
private Button button;
private String callerId;
private String recipientId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
callerId = intent.getStringExtra("callerId");
recipientId = intent.getStringExtra("recipientId");
sinchClient = Sinch.getSinchClientBuilder()
.context(MainActivity.this)
.userId("172976")
.applicationKey(APP_KEY)
.applicationSecret(APP_SECRET)
.environmentHost(ENVIRONMENT)
.build();
sinchClient.setSupportCalling(true);
sinchClient.startListeningOnActiveConnection();
sinchClient.start();
// sinchClient.getCallClient().addCallClientListener(new SinchCallClientListener());
button = findViewById(R.id.button);
callState = findViewById(R.id.callState);
button.setOnClickListener(view -> {
if (call == null) {
try {
boolean s=isStarted();
Log.d("checksinch", String.valueOf(s));
CallClient callClient = sinchClient.getCallClient();
callClient.callPhoneNumber("+16315192247"); // Error occur at this line "SinchClient not started"
//callClient.callPhoneNumber("+16315192247");
// call = sinchClient.getCallClient().callPhoneNumber("+46000000000.");
// call.addCallListener(new SinchCallListener());
button.setText("Hang Up");
}catch (Exception e){
Log.d("checksinch", e.getMessage());
}
} else {
call.hangup();
button.setText("Call");
}
});
}
private boolean isStarted() {
return (sinchClient != null && sinchClient.isStarted());
}
private class SinchCallListener implements CallListener {
#Override
public void onCallEnded(Call endedCall) {
call = null;
SinchError a = endedCall.getDetails().getError();
button.setText("Call");
callState.setText("");
setVolumeControlStream(AudioManager.USE_DEFAULT_STREAM_TYPE);
}
#Override
public void onCallEstablished(Call establishedCall) {
callState.setText("connected");
setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
}
#Override
public void onCallProgressing(Call progressingCall) {
callState.setText("ringing");
}
#Override
public void onShouldSendPushNotification(Call call, List<PushPair> pushPairs) {
}
}
private class SinchCallClientListener implements CallClientListener {
#Override
public void onIncomingCall(CallClient callClient, Call incomingCall) {
call = incomingCall;
Toast.makeText(MainActivity.this, "incoming call", Toast.LENGTH_SHORT).show();
call.answer();
call.addCallListener(new SinchCallListener());
button.setText("Hang Up");
}
}
}

Saripaar Validation library throws No rules found error

I'm trying to use Saripaar Validation on my project, but it's throwing the following error:
java.lang.IllegalStateException: No rules found. You must have at
least one rule to validate. If you are using custom annotations, make
sure that you have registered them using the 'Validator.register()'
method.
My architecture separates the responsibility for handling the view into a class, for example for LoginActivity I have LoginView, which is where I handle my view logic like ButterKnife injection, event listening, etc. In this class I have my annotated fields.My LoginView looks like this:
import android.content.res.ColorStateList;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.ImageViewCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatEditText;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import com.mobsandgeeks.saripaar.ValidationError;
import com.mobsandgeeks.saripaar.Validator;
import com.mobsandgeeks.saripaar.annotation.Email;
import com.mobsandgeeks.saripaar.annotation.NotEmpty;
import com.mobsandgeeks.saripaar.annotation.Password;
import com.serti.android.feenicia.validatortest.R;
import com.serti.android.feenicia.validatortest.screen.login.LoginActivity;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import rx.Observable;
import rx.subjects.PublishSubject;
public class LoginView implements Validator.ValidationListener {
public static final String LOGIN_ACTION = "LOGIN";
#BindView(R.id.login_button)
Button loginButton;
#BindView(R.id.username_edittext)
#NotEmpty
#Email
AppCompatEditText usernameEditText;
#BindView(R.id.password_edittext)
#Password(min = 8, scheme = Password.Scheme.ALPHA_NUMERIC_MIXED_CASE_SYMBOLS)
AppCompatEditText passwordEditText;
#BindView(R.id.eye_imageview)
ImageView eyeImageView;
#BindView(R.id.loading_progressbar)
ProgressBar loadingProgressBar;
private boolean passwordIsVisible;
private AlertDialog confirmPaymentDialog;
private LoginActivity context;
private View rootView;
private PublishSubject<String> clickSubject = PublishSubject.create();
Validator validator;
public LoginView(LoginActivity context){
this.context = context;
FrameLayout parent = new FrameLayout(context);
parent.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
rootView = LayoutInflater.from(context).inflate(R.layout.activity_login, parent, true);
ButterKnife.bind(this, rootView);
validator = new Validator(context);
validator.setValidationListener(this);
eyeImageView.setOnClickListener(v -> handleClick(v.getId()));
loginButton.setOnClickListener(v -> handleClick(v.getId()));
passwordIsVisible = false;
}
#Override
public void onValidationSucceeded() {
String action = null;
Snackbar.make(rootView, "Validated", Snackbar.LENGTH_LONG).show();
loginButton.setVisibility(View.GONE);
loadingProgressBar.setVisibility(View.VISIBLE);
action = LOGIN_ACTION;
if(action != null){
clickSubject.onNext(action);
}
}
#Override
public void onValidationFailed(List<ValidationError> errors) {
for(ValidationError error : errors){
View view = error.getView();
String message = error.getCollatedErrorMessage(context);
if(view instanceof AppCompatEditText){
((AppCompatEditText) view).setError(message);
} else {
Snackbar.make(view, message, Snackbar.LENGTH_LONG).show();
}
}
}
public String getUserName(){
return usernameEditText.getText().toString();
}
public String getPassword(){
return passwordEditText.getText().toString();
}
private void handleClick(int id){
String action = null;
switch (id){
case R.id.login_button:
validator.validate();
break;
case R.id.eye_imageview:
togglePasswordVisibility();
}
}
private void togglePasswordVisibility(){
int color = 0;
if(passwordIsVisible){
passwordEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());
// eyeImageView.setImageDrawable(context.getResources().getDrawable(R.drawable.eye_white));
color = ContextCompat.getColor(context, R.color.dark_blue_button);
ImageViewCompat.setImageTintList(eyeImageView, ColorStateList.valueOf(color));
}else{
passwordEditText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
// eyeImageView.setImageDrawable(context.getResources().getDrawable(R.drawable.eye_white));
color = ContextCompat.getColor(context, R.color.dark_gray);
}
ImageViewCompat.setImageTintList(eyeImageView, ColorStateList.valueOf(color));
passwordIsVisible = !passwordIsVisible;
passwordEditText.setSelection(passwordEditText.getText().length());
}
private void showIncompleteCredentialsMessage() {
Snackbar.make(loginButton, context.getText(R.string.incomplete_credentials_title), Snackbar.LENGTH_LONG).show();
}
public View getView(){
return rootView;
}
public Observable<String> observeClicks(){
return clickSubject;
}
public void openMainScreen(){
context.startMainActivity();
}
public void openSearchTicketsScreen() {
context.startSearchTicketsActivity();
}
public void showWrongCredentialsMessage() {
loginButton.setVisibility(View.VISIBLE);
loadingProgressBar.setVisibility(View.GONE);
Snackbar.make(loginButton, context.getText(R.string.wrong_credentials_title), Snackbar.LENGTH_LONG).show();
}
public void setContext(LoginActivity context) {
this.context = context;
}
}
From what I'm guessing, the library is trying to find these fields on my Activity, and since they're not there, then it's throwing this error.
Is there a way use this library accordingly to the architecture I'm handling?
use validator = new Validator(this) in place of validator = new Validator(context);

Not annotated parameter overrides #NonNull parameter

#nonnull error at inflater , any one can solve this error?
im new to android i don't know how to solve this error any solution ?
is it the error of due theme or something else ,do my code have some major issue ?? can you solve this error please. due to this error my code is not working. your help will be highly appreciated
my import in the code is listed below
import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.app.DownloadManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.support.v7.widget.DividerItemDecoration;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import android.support.annotation.Nullable;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import static android.content.Context.DOWNLOAD_SERVICE;
import java.lang.reflect.Type;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.ref.WeakReference;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class FilesListingFragment extends android.support.v4.app.Fragment {
private static final String TAG = "FilesListingFragment";
public static final String PATH_FILES = "http://%s:%s/files";
public static final String PATH_STATUS = "http://%s:%s/status";
public static final String PATH_FILE_DOWNLOAD = "http://%s:%s/file/%s";
private String mSenderIp = null, mSenderSSID;
private ContactSenderAPITask mUrlsTask;
private ContactSenderAPITask mStatusCheckTask;
private String mPort, mSenderName;
static final int CHECK_SENDER_STATUS = 100;
static final int SENDER_DATA_FETCH = 101;
RecyclerView file;
ProgressBar progressBar;
TextView mTextView;
private SenderFilesListingAdapter mFilesAdapter;
private UiUpdateHandler uiUpdateHandler;
private static final int SENDER_DATA_FETCH_RETRY_LIMIT = 3;
private int senderDownloadsFetchRetry = SENDER_DATA_FETCH_RETRY_LIMIT, senderStatusCheckRetryLimit = SENDER_DATA_FETCH_RETRY_LIMIT;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_files_listing, null);
file = (RecyclerView) v.findViewById(R.id.files_list);
progressBar = (ProgressBar) v.findViewById(R.id.loading);
mTextView = (TextView) v.findViewById(R.id.empty_listing_text);
mTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mTextView.setVisibility(View.GONE);
progressBar.setVisibility(View.VISIBLE);
fetchSenderFiles();
}
});
file.setLayoutManager(new LinearLayoutManager(getActivity()));
file.addItemDecoration(new DividerItemDecoration(getResources().getDrawable(R.drawable.lidivider)));/**here is the error */
mFilesAdapter = new SenderFilesListingAdapter(new ArrayList<String>());
file.setAdapter(mFilesAdapter);
uiUpdateHandler = new UiUpdateHandler(this);
return v;
}
public static FilesListingFragment getInstance(String senderIp, String ssid, String senderName, String port) {
FilesListingFragment fragment = new FilesListingFragment();
Bundle data = new Bundle();
data.putString("senderIp", senderIp);
data.putString("ssid", ssid);
data.putString("name", senderName);
data.putString("port", port);
fragment.setArguments(data);
return fragment;
}
#Override
public void onAttach(Context activity) {
super.onAttach(activity);
if (null != getArguments()) {
mSenderIp = getArguments().getString("senderIp");
mSenderSSID = getArguments().getString("ssid");
mPort = getArguments().getString("port");
mSenderName = getArguments().getString("name");
Log.d(TAG, "sender ip: " + mSenderIp);
}
}
#Override
public void onResume() {
super.onResume();
fetchSenderFiles();
checkSenderAPIAvailablity();
}
private void fetchSenderFiles() {
progressBar.setVisibility(View.VISIBLE);
if (null != mUrlsTask)
mUrlsTask.cancel(true);
mUrlsTask = new ContactSenderAPITask(SENDER_DATA_FETCH);
mUrlsTask.execute(String.format(PATH_FILES, mSenderIp, mPort));
}
private void checkSenderAPIAvailablity() {
if (null != mStatusCheckTask)
mStatusCheckTask.cancel(true);
mStatusCheckTask = new ContactSenderAPITask(CHECK_SENDER_STATUS);
mStatusCheckTask.execute(String.format(PATH_STATUS, mSenderIp, mPort));
}
#Override
public void onPause() {
super.onPause();
if (null != mUrlsTask)
mUrlsTask.cancel(true);
}
#Override
public void onDestroy() {
super.onDestroy();
if (null != uiUpdateHandler)
uiUpdateHandler.removeCallbacksAndMessages(null);
if (null != mStatusCheckTask)
mStatusCheckTask.cancel(true);
}
public String getSenderSSID() {
return mSenderSSID;
}
public String getSenderIp() {
return mSenderIp;
}
private void loadListing(String contentAsString) {
Type collectionType = new TypeToken<List<String>>() {
}.getType();
ArrayList<String> files = new Gson().fromJson(contentAsString, collectionType);
progressBar.setVisibility(View.GONE);
if (null == files || files.size() == 0) {
mTextView.setText("No Downloads found.\n Tap to Retry");
mTextView.setVisibility(View.VISIBLE);
} else {
mTextView.setVisibility(View.GONE);
mFilesAdapter.updateData(files);
}
}
private void onDataFetchError() {
progressBar.setVisibility(View.GONE);
mTextView.setVisibility(View.VISIBLE);
mTextView.setText("Error occurred while fetching data.\n Tap to Retry");
}
private long postDownloadRequestToDM(Uri uri, String fileName) {
// Create request for android download manager
DownloadManager downloadManager = (DownloadManager) getActivity().getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setTitle(fileName);
request.setDescription("ShareThem");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalFilesDir(getActivity(),
Environment.DIRECTORY_DOWNLOADS, fileName);
return downloadManager.enqueue(request);
}
private class SenderFilesListingAdapter extends RecyclerViewArrayAdapter<String, SenderFilesListItemHolder> {
SenderFilesListingAdapter(List<String> objects) {
super(objects);
}
void updateData(List<String> objects) {
clear();
mObjects = objects;
notifyDataSetChanged();
}
#Override
public SenderFilesListItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).
inflate(R.layout.listitem_file, parent, false);
return new SenderFilesListItemHolder(itemView);
}
#Override
public void onBindViewHolder(SenderFilesListItemHolder holder, int position) {
final String senderFile = mObjects.get(position);
holder.itemView.setTag(senderFile);
final String fileName = senderFile.substring(senderFile.lastIndexOf('/') + 1, senderFile.length());
holder.title.setText(fileName);
holder.download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
postDownloadRequestToDM(Uri.parse(String.format(PATH_FILE_DOWNLOAD, mSenderIp, mPort, mObjects.indexOf(senderFile))), fileName);
Toast.makeText(getActivity(), "Downloading " + fileName + "...", Toast.LENGTH_SHORT).show();
}
});
}
}
static class SenderFilesListItemHolder extends RecyclerView.ViewHolder {
TextView title;
ImageButton download;
SenderFilesListItemHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.sender_list_item_name);
download = (ImageButton) itemView.findViewById(R.id.sender_list_start_download);
}
}
/**
* Performs network calls to fetch data/status from Sender.
* Retries on error for times bases on values of {#link FilesListingFragment#senderDownloadsFetchRetry}
*/
private class ContactSenderAPITask extends AsyncTask<String, Void, String> {
int mode;
boolean error;
ContactSenderAPITask(int mode) {
this.mode = mode;
}
#Override
protected String doInBackground(String... urls) {
error = false;
try {
return downloadDataFromSender(urls[0]);
} catch (IOException e) {
e.printStackTrace();
error = true;
Log.e(TAG, "Exception: " + e.getMessage());
return null;
}
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
switch (mode) {
case SENDER_DATA_FETCH:
if (error) {
if (senderDownloadsFetchRetry >= 0) {
--senderDownloadsFetchRetry;
if (getView() == null || getActivity() == null || null == uiUpdateHandler)
return;
uiUpdateHandler.removeMessages(SENDER_DATA_FETCH);
uiUpdateHandler.sendMessageDelayed(uiUpdateHandler.obtainMessage(mode), 800);
return;
} else senderDownloadsFetchRetry = SENDER_DATA_FETCH_RETRY_LIMIT;
if (null != getView())
onDataFetchError();
} else if (null != getView())
loadListing(result);
else Log.e(TAG, "fragment may have been removed, File fetch");
break;
case CHECK_SENDER_STATUS:
if (error) {
if (senderStatusCheckRetryLimit > 1) {
--senderStatusCheckRetryLimit;
uiUpdateHandler.removeMessages(CHECK_SENDER_STATUS);
uiUpdateHandler.sendMessageDelayed(uiUpdateHandler.obtainMessage(CHECK_SENDER_STATUS), 800);
} else if (getActivity() instanceof ReceiverActivity) {
senderStatusCheckRetryLimit = SENDER_DATA_FETCH_RETRY_LIMIT;
((ReceiverActivity) getActivity()).resetSenderSearch();
Toast.makeText(getActivity(), getString(R.string.p2p_receiver_error_sender_disconnected), Toast.LENGTH_SHORT).show();
} else
Log.e(TAG, "Activity is not instance of ReceiverActivity");
} else if (null != getView()) {
senderStatusCheckRetryLimit = SENDER_DATA_FETCH_RETRY_LIMIT;
uiUpdateHandler.removeMessages(CHECK_SENDER_STATUS);
uiUpdateHandler.sendMessageDelayed(uiUpdateHandler.obtainMessage(CHECK_SENDER_STATUS), 1000);
} else
Log.e(TAG, "fragment may have been removed: Sender api check");
break;
}
}
private String downloadDataFromSender(String apiUrl) throws IOException {
InputStream is = null;
try {
URL url = new URL(apiUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response =
conn.getResponseCode();
Log.d(TAG, "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
return readIt(is);
} finally {
if (is != null) {
is.close();
}
}
}
private String readIt(InputStream stream) throws IOException {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(
new InputStreamReader(stream, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
stream.close();
}
return writer.toString();
}
}
private static class UiUpdateHandler extends Handler {
WeakReference<FilesListingFragment> mFragment;
UiUpdateHandler(FilesListingFragment fragment) {
mFragment = new WeakReference<>(fragment);
}
#Override
public void handleMessage(Message msg) {
FilesListingFragment fragment = mFragment.get();
if (null == mFragment)
return;
switch (msg.what) {
case CHECK_SENDER_STATUS:
fragment.checkSenderAPIAvailablity();
break;
case SENDER_DATA_FETCH:
fragment.fetchSenderFiles();
break;
}
}
}
fragment_files_listing
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
tools:context=".receiver.FilesListingFragment"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/files_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
<ProgressBar xmlns:android="http://schemas.android.com/apk/res/android"
style="#android:style/Widget.Holo.ProgressBar"
android:layout_width="wrap_content"
android:id="#+id/loading"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_gravity="center" />
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/empty_listing_text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:clickable="true"
android:gravity="center"
android:text="No Downloads found.\n Tap to Retry"
android:visibility="gone" />
</RelativeLayout>
Not annotated parameter overrides #NonNull parameter
This is just a warning. You have
#Override
public View onCreateView(LayoutInflater inflater...
while the base class you're extending has nullity annotation on the inflater parameter.
public View onCreateView(#NonNull LayoutInflater inflater...
You can just alt-enter in Android Studio to get a quick fix menu that has the option to add the missing annotation there.
due to this error my code is not working.
Missing an annotation like that just causes a warning. The reason for "not working" is something else. Please start by updating your question and specifying what "not working" means to you here.
Try to change this line
View v = inflater.inflate(R.layout.fragment_files_listing, null);
to
View v = inflater.inflate(R.layout.fragment_files_listing, container, false);
This will inflate your layout with your fragment container.
You have to change this line
View v = inflater.inflate(R.layout.fragment_files_listing, null);
to
View v = inflater.inflate(R.layout.fragment_files_listing, container, false);
and then clean your project and invalidate cache restart you android studio.

Dynamically add and animate new ListView item on the beginning - scrolling issue

I have a ListFragment, with a simple ListView. I'm adding new items to this ListView dynamically, when there is a new message on a WebSocket. I'm adding the new row to the beginning of my ArrayAdapter, and there is a simple animation when new item added.
The problem is, when animation is going on, and I'm trying to scroll, older items are also animated on the ListView, only when I'm scrolling fast.
Here is the ListAdapter:
package adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import custom_view.CompassView;
import hu.horadiz.ehoghu.blitzinfo.R;
import logger.AndroidLogger;
import model.BlitzLive;
/**
* Created by ehog on 2014.08.13..
*/
public class LiveArrayAdapter extends ArrayAdapter<BlitzLive> {
private ArrayList<BlitzLive> mLiveData;
private Context mContext;
private String[] mCompass;
private Integer mRecentAddedIndex;
private BlitzLive mRecentAdded;
private boolean mRecentAnimated;
private final static DateFormat DATE_FORMAT = new SimpleDateFormat("HH:MM:SS");
public LiveArrayAdapter(Context context, ArrayList<BlitzLive> mLiveData) {
super(context, 0, mLiveData);
this.mLiveData = mLiveData;
this.mContext = context;
mCompass = mContext.getResources().getStringArray(R.array.compass);
}
#Override
public synchronized void add(BlitzLive object) {
mLiveData.add(0,object);
if (mLiveData.size() > 120)
{
mLiveData.remove(mLiveData.size()-1);
}
mRecentAddedIndex = 0;
mRecentAnimated = true;
mRecentAdded = object;
notifyDataSetChanged();
}
private String coords(Double lat, Double lng)
{
String latitude_text = lat >= 0 ? mCompass[0] : mCompass[8];
String longitude_text = lng >= 0 ? mCompass[4] : mCompass[12];
DecimalFormat nf = new DecimalFormat();
DecimalFormatSymbols p=new DecimalFormatSymbols();
p.setDecimalSeparator('.');
nf.setDecimalFormatSymbols(p);
nf.setMaximumFractionDigits(3);
nf.setMinimumFractionDigits(3);
return String.format("%s %s, %s %s",nf.format(lat),latitude_text,nf.format(lng),longitude_text);
}
#Override
public int getCount() {
return mLiveData.size();
}
#Override
public synchronized View getView(int i, View view, ViewGroup viewGroup) {
if (view == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.holder_blitzes_live, null);
}
TextView settlem = (TextView)view.findViewById(R.id.live_settlem);
TextView data = (TextView)view.findViewById(R.id.live_data);
TextView distancemarker = (TextView)view.findViewById(R.id.live_distancemarker);
DecimalFormat nf = new DecimalFormat();
DecimalFormatSymbols p=new DecimalFormatSymbols();
p.setDecimalSeparator('.');
nf.setDecimalFormatSymbols(p);
nf.setMaximumFractionDigits(2);
nf.setMinimumFractionDigits(2);
if (!mLiveData.get(i).Settlement.equals(""))
{
settlem.setText(mLiveData.get(i).Settlement);
data.setText(String.format("%s km, %s (%s)", nf.format(mLiveData.get(i).Distance), mCompass[(int)((((mLiveData.get(i).Bearing + 11.0) / 22.5) % 16))],coords(mLiveData.get(i).Latitude,mLiveData.get(i).Longitude)));
}
else
{
settlem.setText(coords(mLiveData.get(i).Latitude,mLiveData.get(i).Longitude));
data.setText(String.format("%s km, %s", nf.format(mLiveData.get(i).Distance), mCompass[(int)((((mLiveData.get(i).Bearing + 11.0) / 22.5) % 16))]));
}
CompassView compass = (CompassView)view.findViewById(R.id.live_compass);
compass.setBaseBearing(new Float(mLiveData.get(i).Bearing));
ImageView flag = (ImageView)view.findViewById(R.id.live_flag);
if (mLiveData.get(i).CountryCode.equals("--"))
{
flag.setImageResource(mContext.getResources().getIdentifier(String.format("_cf_big_%s","empty"), "drawable", "hu.horadiz.ehoghu.blitzinfo"));
}
else
{
flag.setImageResource(mContext.getResources().getIdentifier(String.format("_cf_big_%s", mLiveData.get(i).CountryCode), "drawable", "hu.horadiz.ehoghu.blitzinfo"));
}
if (mLiveData.get(i).Distance >= 1000.0)
{
distancemarker.setBackgroundResource(R.drawable.groupedblitzes_count_background_1000plus);
}
else if (mLiveData.get(i).Distance >= 200.0 && mLiveData.get(i).Distance < 1000.0)
{
distancemarker.setBackgroundResource(R.drawable.groupedblitzes_count_background_200plus);
}
else if (mLiveData.get(i).Distance >= 50.0 && mLiveData.get(i).Distance < 200.0)
{
distancemarker.setBackgroundResource(R.drawable.groupedblitzes_count_background_50plus);
}
else if (mLiveData.get(i).Distance >= 20.0 && mLiveData.get(i).Distance < 50.0)
{
distancemarker.setBackgroundResource(R.drawable.groupedblitzes_count_background_20plus);
}
else if (mLiveData.get(i).Distance >= 5.0 && mLiveData.get(i).Distance < 20.0)
{
distancemarker.setBackgroundResource(R.drawable.groupedblitzes_count_background_5plus);
}
else if (mLiveData.get(i).Distance >= 0.0 && mLiveData.get(i).Distance < 5.0)
{
distancemarker.setBackgroundResource(R.drawable.groupedblitzes_count_background_0plus);
}
//This if is false when the wrong item is animates, but the animation is still occurs
if (mRecentAddedIndex == i && mRecentAnimated && mRecentAdded.equals(mLiveData.get(i)))
{
mRecentAnimated = false;
Animation ANIM_APPEAR = AnimationUtils.loadAnimation(getContext(), R.anim.push_right_in);
ANIM_APPEAR.setDuration(500);
view.findViewById(R.id.live_holder_parent).startAnimation(ANIM_APPEAR);
AndroidLogger.PushDebugMessage("Animáció megtörtént: "+mRecentAddedIndex+" "+mLiveData.get(i).Settlement);
}
return view;
}
}
and the ListFragment:
package fragments;
import android.app.Fragment;
import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.json.JSONObject;
import java.util.ArrayList;
import adapters.LiveArrayAdapter;
import hu.horadiz.ehoghu.blitzinfo.R;
import logger.AndroidLogger;
import model.BlitzLive;
import using_net.BlitzLiveDataAsyncTask;
/**
* Created by ehog on 2014.08.12..
*/
public class LiveDataFragment extends ListFragment implements BlitzLiveDataAsyncTask.OnMessage
{
private BlitzLiveDataAsyncTask _mLiveAsyncTask;
private LiveArrayAdapter mListAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.fragment_live, container, false);
return v;
}
#Override
public void onCreate(Bundle savedInstanceState)
{
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
mListAdapter = new LiveArrayAdapter(getActivity(),new ArrayList<BlitzLive>());
mListAdapter.setNotifyOnChange(true);
setListAdapter(mListAdapter);
}
#Override
public void onStart()
{
if (getActivity() != null)
{
getActivity().setTitle(getActivity().getResources().getString(R.string.title_liveview));
}
super.onStart();
if (_mLiveAsyncTask != null)
{
_mLiveAsyncTask.cancel(true);
}
_mLiveAsyncTask = new BlitzLiveDataAsyncTask(this);
_mLiveAsyncTask.execute();
}
#Override
public void onPause() {
super.onPause();
if (_mLiveAsyncTask != null)
{
_mLiveAsyncTask.stop();
_mLiveAsyncTask.cancel(true);
AndroidLogger.PushDebugMessage("onPause cancel");
}
}
#Override
public void onCreateOptionsMenu (Menu menu, MenuInflater inflater)
{
menu.clear();
inflater.inflate(R.menu.blitz_live, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public void onMessage(final JSONObject message)
{
getActivity().runOnUiThread(new Runnable() {
public void run() {
((LiveArrayAdapter)getListAdapter()).add(BlitzLive.fromJSON(message));
}
});
AndroidLogger.PushDebugMessage(String.format("Websocket message: %s", message.toString()));
}
}
yes recycling is the problem. When you add the animation in your adapter, you have to put a "remove animation code":
if (mRecentAddedIndex == i && mRecentAnimated && mRecentAdded.equals(mLiveData.get(i)))
{
mRecentAnimated = false;
Animation ANIM_APPEAR = AnimationUtils.loadAnimation(getContext(), R.anim.push_right_in);
ANIM_APPEAR.setDuration(500);
view.findViewById(R.id.live_holder_parent).startAnimation(ANIM_APPEAR);
AndroidLogger.PushDebugMessage("Animáció megtörtént: "+mRecentAddedIndex+" "+mLiveData.get(i).Settlement);
} else {
// remove animation
The final code: (cleaned, animation went final, etc etc)
if (mRecentAddedIndex == i && mRecentAnimated && mRecentAdded.equals(mLiveData.get(i)))
{
mRecentAnimated = false;
layout.startAnimation(ANIM_APPEAR);
AndroidLogger.PushDebugMessage("Animáció megtörtént (Animation occurred): "+mRecentAddedIndex+" "+mLiveData.get(i).Settlement);
}
else
{
layout.clearAnimation();
}

Making a call when button pressed on Arduino

Hi I'm trying to combine 2 projects
1. that tells me wen button on arduino pressed
2. make a call on android
what im trying to do is when button pressed on arduino make a call..
but with no luck :(
Call
package net.mitchtech.adb;
import net.mitchtech.adb.simpledigitalinput.R;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
public class phonecalls extends Activity {
private void call() {
try {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:048598077"));
startActivity(callIntent);
} catch (ActivityNotFoundException activityException) {
Log.e("dialing-example", "Call failed", activityException);
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.input);
}
}
buttons
package net.mitchtech.adb;
import net.mitchtech.adb.simpledigitalinput.R;
import net.mitchtech.adb.phonecalls;
import org.microbridge.server.AbstractServerListener;
import org.microbridge.server.Server;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
public class ButtonView extends FrameLayout {
private static final String TAG = ButtonView.class.getSimpleName();
private final View mButtonView;
private Server mServer;
private final int BUTTON1 = 2;
private final int BUTTON2 = 3;
public ButtonView(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mButtonView = inflater.inflate(R.layout.input, this);
}
public void setServer(Server server) {
mServer = server;
mServer.addListener(new AbstractServerListener() {
#Override
public void onReceive(org.microbridge.server.Client client, byte[] data) {
if (data.length < 2)
return;
final int pinNumber = data[0];
final int pinState = data[1];
Log.i(TAG, "data[0]:" + pinNumber + " data[1]:" + pinState);
final TextView positionText = (TextView) findViewById(R.id.activeText);
class InputAction implements Runnable {
public void run() {
switch (pinNumber) {
case BUTTON1:
if (pinState == 1) {
call();
positionText.setText("Button 1 Active");
} else {
positionText.setText("");
}
break;
case BUTTON2:
if (pinState == 1) {
positionText.setText("Button 2 Active");
} else {
positionText.setText("");
}
break;
default:
break;
}
}
};
InputAction action = new InputAction();
post(action);
}
});
}
public View getmButtonView() {
return mButtonView;
}
}
and another activity
package net.mitchtech.adb;
import java.io.IOException;
import net.mitchtech.adb.simpledigitalinput.R;
import org.microbridge.server.Server;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class SimpleDigitalInputActivity extends Activity {
private final static String TAG = SimpleDigitalInputActivity.class.getSimpleName();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Server server = null;
try
{
server = new Server(4567);
server.start();
ButtonView buttonView = (ButtonView) findViewById(R.id.inputView);
buttonView.setServer(server);
} catch (IOException e)
{
Log.e(TAG, "Unable to start TCP server", e);
System.exit(-1);
}
}
}
Your call() function is declared in your activity, but you're trying to access it in your ButtonView class. Try moving it into ButtonView (copy & paste).

Categories

Resources