Unity and Android Studio integration hardware not supported - android

I have attempted to integrate simple Unity shape figure to display using Android Studio IDE however it shows like this:
Your hardware does not support this application sorry
My phone is Android 6.0 Marshmallow and the version of Unity is 5.4.1f1
The logcat in Android Studio does not show any error except when I dismiss the message about hardware not supported, then crashed.
package com.cs4.android_lcitresearch.schoolsafetyemergencyapplication.maps_class;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.TextView;
import com.cs4.android_lcitresearch.schoolsafetyemergencyapplication.R;
import com.cs4.android_lcitresearch.schoolsafetyemergencyapplication.SplashInterface;
import com.cs4.android_lcitresearch.schoolsafetyemergencyapplication.comic_class.comiclass;
import com.cs4.android_lcitresearch.schoolsafetyemergencyapplication.phone_class.phoneclass;
import com.cs4.android_lcitresearch.schoolsafetyemergencyapplication.scenario_class.scenarioclass;
import com.unity3d.player.UnityPlayer;
public class lcoldclass extends AppCompatActivity {
protected UnityPlayer mUnityPlayer;
public static Context mContext;
private Handler handler=new Handler();
public FrameLayout fl_forUnity;
public ImageButton scenario1, comic1, phoneclass1, maps1, homeb;
public Toolbar toolbar;
public TextView txttitle;
public void init_home() {
homeb= (ImageButton)findViewById(R.id.homebutton);
homeb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent first = new Intent(lcoldclass.this,SplashInterface.class);
startActivity(first);
}
});
}
public void init_scenario() {
scenario1= (ImageButton)findViewById(R.id.scenario);
scenario1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent first = new Intent(lcoldclass.this,scenarioclass.class);
startActivity(first);
}
});
}
public void init_comic() {
comic1= (ImageButton)findViewById(R.id.comicbutton);
comic1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent first = new Intent(lcoldclass.this,comiclass.class);
startActivity(first);
}
});
}
public void init_phone() {
phoneclass1= (ImageButton)findViewById(R.id.callbutton);
phoneclass1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent first = new Intent(lcoldclass.this,phoneclass.class);
startActivity(first);
}
});
}
public void init_maps() {
maps1= (ImageButton)findViewById(R.id.mapsl);
maps1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent first = new Intent(lcoldclass.this,SecondInterfaceF.class);
startActivity(first);
}
});
}
private void initToolbar() {
toolbar = (Toolbar) findViewById(R.id.include2);
toolbar.showOverflowMenu();
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
mContext = this;
getWindow().takeSurface(null);
setTheme(android.R.style.Theme_NoTitleBar_Fullscreen);
getWindow().setFormat(PixelFormat.RGB_888);
mUnityPlayer = new UnityPlayer(this);
if (mUnityPlayer.getSettings ().getBoolean ("hide_status_bar", true))
getWindow ().setFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
int glesMode = mUnityPlayer.getSettings().getInt("gles_mode", 1);
boolean trueColor8888 = false;
mUnityPlayer.init(glesMode, trueColor8888);
View playerView = mUnityPlayer.getView();
setContentView(R.layout.lcmapsold1);
this.fl_forUnity = (FrameLayout)findViewById(R.id.frameunity);
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(750, 630);
fl_forUnity.addView(playerView, 0, lp);
initToolbar();
init_home();
init_scenario();
init_comic();
init_phone();
init_maps();
txtformation_init();
mUnityPlayer.requestFocus();
}
///////////////////////////// Unity Codes Override///////////////////////////////////////////
// Quit Unity
#Override protected void onDestroy ()
{
mUnityPlayer.quit();
super.onDestroy();
}
// Pause Unity
#Override protected void onPause()
{
super.onPause();
mUnityPlayer.pause();
}
// Resume Unity
#Override protected void onResume()
{
super.onResume();
mUnityPlayer.resume();
}
// This ensures the layout will be correct.
#Override public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
mUnityPlayer.configurationChanged(newConfig);
}
// Notify Unity of the focus change.
#Override public void onWindowFocusChanged(boolean hasFocus)
{
super.onWindowFocusChanged(hasFocus);
mUnityPlayer.windowFocusChanged(hasFocus);
}
// For some reason the multiple keyevent type is not supported by the ndk.
// Force event injection by overriding dispatchKeyEvent().
#Override public boolean dispatchKeyEvent(KeyEvent event)
{
if (event.getAction() == KeyEvent.ACTION_MULTIPLE)
return mUnityPlayer.injectEvent(event);
return super.dispatchKeyEvent(event);
}
// Pass any events not handled by (unfocused) views straight to UnityPlayer
#Override public boolean onKeyUp(int keyCode, KeyEvent event) { return mUnityPlayer.injectEvent(event); }
#Override public boolean onKeyDown(int keyCode, KeyEvent event) { return mUnityPlayer.injectEvent(event); }
#Override public boolean onTouchEvent(MotionEvent event) { return mUnityPlayer.injectEvent(event); }
/*API12*/ public boolean onGenericMotionEvent(MotionEvent event) { return mUnityPlayer.injectEvent(event); }
///////////////////////////// Unity Codes Override///////////////////////////////////////////
}
How to solve it? I cannot understand how users manage to work the program without issues on integration.

Related

onSupportNavigateUp() function not working?

All my pages use onSupportNavigateUp() function with the same method and it's working. However when I tried to implement in my LessonActivity.java it's not working. Any ideas? It's it because of WebView?
My current working codes for LessonActivity.java:
package com.activity.lesson;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatRatingBar;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ServerValue;
import com.google.firebase.database.ValueEventListener;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.material.components.R;
import com.material.components.activity.pastyears.PastYears;
import com.material.components.activity.practice.Practice;
import com.material.components.adapter.AdapterQuestionToTeacher;
import com.material.components.model.Lessons;
import com.material.components.model.QuestionsToTeacher;
import com.material.components.model.SubChapter;
import com.material.components.utils.Tools;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class LessonActivity extends AppCompatActivity{
public WebView contentWebView;
public ProgressBar progressBar;
public String chapterTitle;
private SharedPreferences analysisSharedPreferences;
private SharedPreferences.Editor editorAnalysisPreferences;
private BottomSheetBehavior mBehavior;
private BottomSheetDialog mBottomSheetDialog;
private View bottom_sheet;
private BottomNavigationView navigation;
public ArrayList<QuestionsToTeacher> questionsToTeacherList = new ArrayList<>();
private AdapterQuestionToTeacher adapterQuestionToTeacher;
private RecyclerView questionListRecyclerView;
private String subjectId;
private String chapterId;
private String subchapterId;
private TextView question_content;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lesson);
contentWebView = findViewById(R.id.contentWebView);
progressBar = findViewById(R.id.progressBarContent);
question_content = findViewById(R.id.question_content);
Tools.setSystemBarColor(this,R.color.black);
String qContent = question_content.getText().toString().trim();
if(qContent.isEmpty())
{
question_content.setVisibility(View.GONE);
}else
{
question_content.setVisibility(View.VISIBLE);
}
initToolbar();
String subChapterId = getIntent().getStringExtra("subchapter_id");
getLessonData(subChapterId);
analysisSharedPreferences = getApplicationContext().getSharedPreferences("AnalysisSharedPreferences",MODE_PRIVATE);
editorAnalysisPreferences = analysisSharedPreferences.edit();
subjectId = analysisSharedPreferences.getString("subjectId","");
chapterId = analysisSharedPreferences.getString("chapterId","");
subchapterId = analysisSharedPreferences.getString("subchapterId","");
bottom_sheet = findViewById(R.id.bottom_sheet);
mBehavior = BottomSheetBehavior.from(bottom_sheet);
navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_question_list:
showQuestionList();
return true;
}
return false;
}
});
}
private void getQuestionList() {
GsonBuilder builder = new GsonBuilder();
final Gson gson = builder.create();
questionsToTeacherList.clear();
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference databaseReference = firebaseDatabase.getReference();
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
databaseReference.child("ask_teachers/students/"+firebaseAuth.getUid()+"/subjects/"+subjectId+"/chapters/"+chapterId+"/subchapters/"+subchapterId+"/questions").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot: dataSnapshot.getChildren())
{
String dataReceived = gson.toJson(snapshot.getValue());
System.out.println(snapshot.getValue());
QuestionsToTeacher questionsToTeacher = gson.fromJson(dataReceived,QuestionsToTeacher.class);
questionsToTeacherList.add(questionsToTeacher);
}
adapterQuestionToTeacher.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void showQuestionList() {
if (mBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
mBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
}
final View view = getLayoutInflater().inflate(R.layout.sheet_question_list, null);
adapterQuestionToTeacher = new AdapterQuestionToTeacher(questionsToTeacherList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(LessonActivity.this);
questionListRecyclerView = view.findViewById(R.id.questionListRecyclerView);
questionListRecyclerView.setItemAnimator(new DefaultItemAnimator());
questionListRecyclerView.setNestedScrollingEnabled(false);
questionListRecyclerView.setHasFixedSize(true);
questionListRecyclerView.setLayoutManager(layoutManager);
questionListRecyclerView.setAdapter(adapterQuestionToTeacher);
adapterQuestionToTeacher.setOnClickListener(new AdapterQuestionToTeacher.OnClickListener() {
#Override
public void onItemClick(View view, QuestionsToTeacher obj, int pos) {
question_content.setVisibility(View.VISIBLE);
question_content.setText(obj.messages);
mBottomSheetDialog.dismiss();
}
});
(view.findViewById(R.id.bt_close)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mBottomSheetDialog.dismiss();
}
});
mBottomSheetDialog = new BottomSheetDialog(this);
mBottomSheetDialog.setContentView(view);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mBottomSheetDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
mBottomSheetDialog.show();
mBottomSheetDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
mBottomSheetDialog = null;
}
});
getQuestionList();
}
private void getLessonData(String subChapterId)
{
FirebaseDatabase.getInstance().getReference().child("lessons/"+subChapterId+"/lessons_data")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String lessonDisplay = "";
for(DataSnapshot snapshot: dataSnapshot.getChildren())
{
System.out.println("lesson_inner_content");
System.out.println(snapshot.getValue());
lessonDisplay += snapshot.getValue();
}
contentWebView.getSettings().setJavaScriptEnabled(true);
contentWebView.setWebViewClient(new AppWebViewClients(progressBar));
contentWebView.loadData(String.valueOf(lessonDisplay),"text/html", "UTF-8");
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public class AppWebViewClients extends WebViewClient {
private ProgressBar progressBar;
public AppWebViewClients(ProgressBar progressBar) {
this.progressBar=progressBar;
progressBar.setVisibility(View.VISIBLE);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
}
}
private void initToolbar() {
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
chapterTitle = getIntent().getStringExtra("subChapterTitle");
setTitle(chapterTitle);
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
public void openSubMenu(View v)
{
PopupMenu popup = new PopupMenu(v.getContext(), v);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.menu_lesson_more, popup.getMenu());
popup.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_lesson,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.askTeacher)
{
showQuestionEntryDialog();
}
if(id == R.id.practice)
{
Intent gotoPractice = new Intent(LessonActivity.this, Practice.class);
startActivity(gotoPractice);
}
if(id == R.id.pastYears)
{
Intent gotoPastYears = new Intent(LessonActivity.this, PastYears.class);
startActivity(gotoPastYears);
}
return true;
}
private void showQuestionEntryDialog() {
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // before
dialog.setContentView(R.layout.dialog_ask_teacher_question_entry);
dialog.setCancelable(true);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
final EditText et_post = dialog.findViewById(R.id.et_post);
dialog.findViewById(R.id.bt_cancel).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.findViewById(R.id.bt_submit).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String review = et_post.getText().toString().trim();
if (review.isEmpty()) {
Toast.makeText(getApplicationContext(), "Please fill review text", Toast.LENGTH_SHORT).show();
}else
{
submitQuestion(review, dialog);
}
}
});
dialog.show();
dialog.getWindow().setAttributes(lp);
}
private void submitQuestion(String message, final Dialog dialog)
{
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
String uuid = currentFirebaseUser.getUid();
DatabaseReference databaseReference = firebaseDatabase.getReference();
HashMap<Object,Object> messagesData = new HashMap<>();
messagesData.put("subject_id",subjectId);
messagesData.put("chapter_id",chapterId);
messagesData.put("subchapter_id",subchapterId);
messagesData.put("messages",message);
messagesData.put("status","pending");
messagesData.put("dt_added", ServerValue.TIMESTAMP);
databaseReference.child("ask_teachers/students/"+uuid+"/subjects/"+subjectId+"/chapters/"+chapterId+"/subchapters/"+subchapterId+"/questions/").push().setValue(messagesData, new DatabaseReference.CompletionListener(){
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
Toast.makeText(LessonActivity.this, "Successfully added to Ask Teacher list", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
}
}
onSupportNavigateUp() is not working because you're also overriding onOptionsItemSelected(). Since you return true; from onOptionsItemSelected(), you basically tell Android that you handle all item clicks by yourself and it doesn't need to do something.
You have two options now. Either call super.onOptionsItemSelected() like:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.askTeacher) {
showQuestionEntryDialog();
return true; // don't forget to return true after your action
}
// ... handle all your other items
return super.onOptionsItemSelected(item);
}
Or you handle the back button click by yourself:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
// navigate up on back button click
if (id == android.R.id.home) {
NavUtils.navigateUpFromSameTask(this);
return true;
}
// ... handle all your other items
return true;
}
By the way, I think overriding onSupportNavigateUp() is not needed at all. Up navigation works "out of the box" (at least for me), as long as I don't override onOptionsItemSelected() or call super.onOptionsItemSelected(item); from within it.

BraintreeHttpClient.setBaseUrl(java.lang.String) on a null object reference

I am using braintree api to get add card in app for payments. It works fines and sometimes crashes randomly,
This is my stacktrace,
E/AndroidRuntime: FATAL EXCEPTION: Thread-833
Process: cl.tempclick, PID: 29509
java.lang.NullPointerException: Attempt to invoke virtual method 'com.braintreepayments.api.internal.HttpClient com.braintreepayments.api.internal.BraintreeHttpClient.setBaseUrl(java.lang.String)' on a null object reference
at com.braintreepayments.api.BraintreeFragment.setConfiguration(BraintreeFragment.java:488)
at com.braintreepayments.api.BraintreeFragment$5.onConfigurationFetched(BraintreeFragment.java:415)
at com.braintreepayments.api.ConfigurationManager.getConfiguration(ConfigurationManager.java:46)
at com.braintreepayments.api.BraintreeFragment.fetchConfiguration(BraintreeFragment.java:412)
at com.braintreepayments.api.BraintreeFragment.waitForConfiguration(BraintreeFragment.java:458)
at com.braintreepayments.api.TokenizationClient.tokenize(TokenizationClient.java:72)
at com.braintreepayments.api.Card.tokenize(Card.java:29)
at cl.tk.ui.activities.sub_activity.AddPayment$UIThreadHandler$1.run(AddPayment.java:364)
at java.lang.Thread.run(Thread.java:818)
This is my Code for the activity,
package cl.tk.ui.activities.sub_activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.braintreepayments.api.BraintreeFragment;
import com.braintreepayments.api.exceptions.InvalidArgumentException;
import com.braintreepayments.api.interfaces.PaymentMethodNonceCreatedListener;
import com.braintreepayments.api.models.CardBuilder;
import com.braintreepayments.api.models.PaymentMethodNonce;
import cl.tk.R;
import cl.tk.controllers.constants.Constants;
import cl.tk.controllers.constants.Enums_String;
import cl.tk.controllers.listeners.ProcessedResult;
import cl.tk.controllers.rest_api.RetrofitAdapters;
import cl.tk.ui.activities.Register;
import cl.tk.ui.fragments.dialog.DTDialog;
import cl.tk.ui.iBAPViews.editext.pattern.PatternedEditText;
import cl.tk.utility.CreditCard;
import cl.tk.utility.CustomException;
import cl.tek.utility.GeneralFunctions;
import cl.tk.utility.MonthYearPicker;
import cl.tk.utility.Validation;
import cl.tk.utility.fonts.FontsManager;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
public class AddPayment extends AppCompatActivity implements View.OnClickListener,View.OnTouchListener, ProcessedResult,PaymentMethodNonceCreatedListener
{
private Handler uiThreadHandler;
private TextView tvExpiryDate;
//private EditText edCvv,ed_cardHOlderName,edZip;
private PatternedEditText edCardNumber;
private MonthYearPicker myp;
private String mClientToken=null;
private CreditCard creditCard =null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_payment);
uiThreadHandler = new UIThreadHandler();
initialze();
downloadBraintreeTOken();
}
private void downloadBraintreeTOken()
{
RetrofitAdapters.get().getBraintreeToken(new Callback<Response>() {
#Override
public void success(Response response, Response response2) {
parseResult(response);
}
#Override
public void failure(RetrofitError error) {
uiThreadHandler.sendEmptyMessage(Constants.ActivityBasicsCode.HIDEDIALOG);
Message message = uiThreadHandler.obtainMessage(Constants.ActivityBasicsCode.SHOWTOAST);
message.obj = error.getLocalizedMessage();
uiThreadHandler.sendMessage(message);
}
});
}
private void initialze()
{
GeneralFunctions.setToolbarMsgIconHide(this, Constants.ToolbarConstants.PAYMENTS, true);
Button buttonAdd=GeneralFunctions.findViewByIdAndCast(this,R.id.payment_bt_addCard);
buttonAdd.setOnClickListener(this);
GeneralFunctions.setColorSelector(ContextCompat.getColor(this, R.color.color175), ContextCompat.getColor(this, R.color.color1A9), buttonAdd);
TextView tv_defult=GeneralFunctions.findViewByIdAndCast(this,R.id.payment_ct_default);
tv_defult.setOnClickListener(this);
FontsManager.initFormAssets(this, Enums_String.FontsNameLato.SEMIBOLD.toString());
FontsManager.changeFonts(tv_defult);
edCardNumber=GeneralFunctions.findViewByIdAndCast(this,R.id.payment_ed_cardNumber);
tvExpiryDate=GeneralFunctions.findViewByIdAndCast(this,R.id.payment_tv_expiryDate);
tvExpiryDate.setOnTouchListener(this);
myp = new MonthYearPicker(this);
myp.build(new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
tvExpiryDate.setText(myp.getSelectedMonth() + 1 + "/" + myp.getSelectedYear());
}
}, null);
}
#Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter(Enums_String.LocalReceiver.INTERENT.toString());
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, filter);
}
#Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.payment_bt_addCard:
uiThreadHandler.sendEmptyMessage(Constants.ActivityBasicsCode.VALIDATION);
break;
}
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP)
{
if(v.getId()==R.id.payment_tv_expiryDate)
{
if(myp.pickerDialog != null && !myp.pickerDialog.isShowing())
myp.pickerDialog.dismiss();
myp.show();
}
return true;
}
return false;
}
#Override
public <IResponse, IMethod, IExtra> void processedResult(IResponse iResponse, IMethod iMethod, IExtra iExtra) {
}
#Override
public <IResponse, IMethod> void processedResult(IResponse iResponse, IMethod iMethod) {
switch (iMethod.toString())
{
case Constants.CallbackConstants.VIEW_ERROR: {
Message message = uiThreadHandler.obtainMessage(Constants.ActivityBasicsCode.SETERROR);
message.obj=iResponse;
uiThreadHandler.sendMessage(message);
}
break;
case Constants.CallbackConstants.BACK:
finish();
break;
}
}
#Override
public void onPaymentMethodNonceCreated(final PaymentMethodNonce paymentMethodNonce) {
}
private void setError(String errorMsg) {
if (errorMsg.equalsIgnoreCase("cardNumber"))
GeneralFunctions.setError(null,String.format(getString(R.string.ed_error_invalid),edCardNumber.getTag().toString()),edCardNumber);
else if (errorMsg.equalsIgnoreCase("cardDate"))
GeneralFunctions.setError(null,String.format(getString(R.string.ed_error_invalid),tvExpiryDate.getTag().toString()),tvExpiryDate);
}
private class UIThreadHandler extends Handler {
#Override
public void handleMessage(Message msg)
{
switch (msg.what) {
case Constants.ActivityBasicsCode.CARDERROR:
GeneralFunctions.setError((CustomException)msg.obj,null,null);
break;
case Constants.ActivityBasicsCode.SETERROR:
setError(msg.obj.toString());
break;
case Constants.ActivityBasicsCode.SHOWTOAST:
{
String text=(String)msg.obj;
GeneralFunctions.showToast(text,AddPayment.this);
}
break;
case Constants.ActivityBasicsCode.HIDEDIALOG:
GeneralFunctions.hideProgressDialog(Constants.DialogConstants.Transparent, AddPayment.this);
break;
case Constants.ActivityBasicsCode.SHOWDIALOG:
{
DTDialog dtDialog=DTDialog.newInstance();
GeneralFunctions.showProgressDialog(dtDialog, Constants.DialogConstants.Transparent, AddPayment.this);
}break;
case Constants.ActivityBasicsCode.VALIDATION: {
new Thread(new Runnable() {
#Override
public void run()
{
try {
if(Validation.validate(AddPayment.this)) {
creditCard = new CreditCard(GeneralFunctions.getText(edCardNumber),GeneralFunctions.getText(tvExpiryDate),AddPayment.this);
boolean validation = creditCard.validateCard();
if (validation) {
if(mClientToken==null) {
downloadBraintreeTOken();
Message message = uiThreadHandler.obtainMessage(Constants.ActivityBasicsCode.SHOWTOAST);
message.obj = getString(R.string.toast_payment_token);
uiThreadHandler.sendMessage(message);
return;
}
BraintreeFragment braintreeFragment= BraintreeFragment.newInstance(AddPayment.this, mClientToken);
if(null==braintreeFragment)
{
Message message = uiThreadHandler.obtainMessage(Constants.ActivityBasicsCode.SHOWTOAST);
message.obj = getString(R.string.toast_payment_fragment);
uiThreadHandler.sendMessage(message);
uiThreadHandler.sendEmptyMessage(Constants.ActivityBasicsCode.SHOWDIALOG);
}
else {
CardBuilder cardBuilder = new CardBuilder()
.cardNumber(creditCard.getNumber().replaceAll("-", "").trim())
.expirationDate(creditCard.getExpriyDate());
com.braintreepayments.api.Card.tokenize(braintreeFragment, cardBuilder); //On this line my app crashes randomly
}
}
}
}catch (CustomException e)
{
Message message = uiThreadHandler.obtainMessage(Constants.ActivityBasicsCode.CARDERROR);
message.obj=e;
uiThreadHandler.sendMessage(message);
} catch (InvalidArgumentException e) {
e.printStackTrace();
}
}
}).start();
break;
}
}
super.handleMessage(msg);
}
}
}
This is my gradle version,
compile 'com.braintreepayments.api:braintree:2.+'
Full disclosure: I work for Braintree.
Are you refreshing the client token every time you go through the checkout process as required? I see that you are only downloading the Braintree token from the server if it is null.
Without having any insight into your CreditCard class or its validateCard method, another possibility may be that the CardBuilder object you are passing into Card.tokenize may not be well-formed.
​
If you are still having trouble, please reach out to Braintree support for help debugging your integration.

Starting new Thread freezes UI

I am working on an app that implements a Web Socket server. I am referring this library - https://github.com/TooTallNate/Java-WebSocket
The problem is that the thread holds up the entire UI. Here is the code -
package com.example.websocket;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Collections;
import java.nio.ByteBuffer;
import org.java_websocket.WebSocket;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_17;
import org.java_websocket.framing.FrameBuilder;
import org.java_websocket.framing.Framedata;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
import android.os.Bundle;
import android.provider.Settings.Global;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText port, msg;
Button listener, send;
TextView status;
int p;
int count = 0;
boolean connect = false;
boolean listen = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
msg = (EditText)findViewById(R.id.editText2);
listener = (Button)findViewById(R.id.button1);
send = (Button)findViewById(R.id.button2);
status = (TextView)findViewById(R.id.textView1);
listener.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
SimpleServer server = new SimpleServer();
server.start();
status.setText("Working inside Thread");
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
});
t.start();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class SimpleServer extends WebSocketServer {
public SimpleServer() throws UnknownHostException {
super(new InetSocketAddress(9998));
// TODO Auto-generated constructor stub
}
#Override
public void onClose(WebSocket arg0, int arg1, String arg2, boolean arg3) {
// TODO Auto-generated method stub
}
#Override
public void onError(WebSocket arg0, Exception arg1) {
// TODO Auto-generated method stub
}
#Override
public void onMessage(WebSocket arg0, String arg1) {
// TODO Auto-generated method stub
}
#Override
public void onOpen(WebSocket arg0, ClientHandshake arg1) {
status.setText("Working");
}
}
}
You cannot update ui from other threads:
status.setText("Working inside Thread");
use runOnUiThread method of activity
runOnUiThread(new Runnable() {
#Override
public void run() {
status.setText("Working inside Thread");
}
});
By the way youre code cause memory leack and crashes. You cannot start long living operations in activity context. You should run service ,or make this thread in application context, results to ui you can pass by using EventBus.

How to change webview orientation in android while coming back from another screen

I am having a screen which has a WebView showing a UI developed in HTML and PHP. Now, when i migrate to a different screen in Android and want to come back to my parent screen, I want to have a NEW WebView layout. Even though I am passing a String variable back for validating purposes, but still then it does not work out. Does this have to do anything with the savedInstanceState? Any suggestions would be appreciated. Below is the code snippet.
package com.example.notifboard;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
public class AdminLogin extends Activity {
boolean flag = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
flag = true;
}
protected void onResume() {
super.onResume();
if (flag == true) {
setContentView(R.layout.adminloginmixed);
final Button AdminBtn = (Button)findViewById(R.id.AdminBtn);
final Button EventGenBtn = (Button)findViewById(R.id.EventGenBtn);
final Button BackBtn = (Button)findViewById(R.id.BackBtn);
AdminBtn.setBackgroundColor(Color.WHITE);
AdminBtn.setTextColor(Color.BLACK);
EventGenBtn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
EventGenBtn.setBackgroundColor(Color.WHITE);
EventGenBtn.setTextColor(Color.BLACK);
AdminBtn.setBackgroundColor(Color.parseColor("#1D326B"));
AdminBtn.setTextColor(Color.WHITE);
BackBtn.setBackgroundColor(Color.parseColor("#1D326B"));
BackBtn.setTextColor(Color.WHITE);
Intent EveGenIntent = new Intent(AdminLogin.this, EventGen.class);
startActivity(EveGenIntent);
finish();
}
});
AdminBtn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
EventGenBtn.setBackgroundColor(Color.parseColor("#1D326B"));
EventGenBtn.setTextColor(Color.WHITE);
BackBtn.setBackgroundColor(Color.parseColor("#1D326B"));
BackBtn.setTextColor(Color.WHITE);
AdminBtn.setBackgroundColor(Color.WHITE);
AdminBtn.setTextColor(Color.BLACK);
}
});
BackBtn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
BackBtn.setBackgroundColor(Color.WHITE);
BackBtn.setTextColor(Color.BLACK);
EventGenBtn.setBackgroundColor(Color.parseColor("#1D326B"));
EventGenBtn.setTextColor(Color.WHITE);
AdminBtn.setBackgroundColor(Color.parseColor("#1D326B"));
AdminBtn.setTextColor(Color.WHITE);
Intent BackBtnIntent = new Intent(AdminLogin.this, SelectEntryType.class);
startActivity(BackBtnIntent);
finish();
}
});
WebView browser = (WebView)findViewById(R.id.Adminloginwebview);
browser.setWebViewClient(new WebViewClient());
browser.loadUrl("http://sivasphpmobileapps.site90.net/NotificationBoard/AdminLogin.php");
}
else {
setContentView(R.layout.adminloginmixed);
final Button AdminBtn = (Button)findViewById(R.id.AdminBtn);
final Button EventGenBtn = (Button)findViewById(R.id.EventGenBtn);
final Button BackBtn = (Button)findViewById(R.id.BackBtn);
AdminBtn.setBackgroundColor(Color.WHITE);
AdminBtn.setTextColor(Color.BLACK);
EventGenBtn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
EventGenBtn.setBackgroundColor(Color.WHITE);
EventGenBtn.setTextColor(Color.BLACK);
AdminBtn.setBackgroundColor(Color.parseColor("#1D326B"));
AdminBtn.setTextColor(Color.WHITE);
BackBtn.setBackgroundColor(Color.parseColor("#1D326B"));
BackBtn.setTextColor(Color.WHITE);
Intent EveGenIntent = new Intent(AdminLogin.this, EventGen.class);
startActivity(EveGenIntent);
}
});
AdminBtn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
EventGenBtn.setBackgroundColor(Color.parseColor("#1D326B"));
EventGenBtn.setTextColor(Color.WHITE);
BackBtn.setBackgroundColor(Color.parseColor("#1D326B"));
BackBtn.setTextColor(Color.WHITE);
AdminBtn.setBackgroundColor(Color.WHITE);
AdminBtn.setTextColor(Color.BLACK);
}
});
BackBtn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
BackBtn.setBackgroundColor(Color.WHITE);
BackBtn.setTextColor(Color.BLACK);
EventGenBtn.setBackgroundColor(Color.parseColor("#1D326B"));
EventGenBtn.setTextColor(Color.WHITE);
AdminBtn.setBackgroundColor(Color.parseColor("#1D326B"));
AdminBtn.setTextColor(Color.WHITE);
Intent BackBtnIntent = new Intent(AdminLogin.this, SelectEntryType.class);
startActivity(BackBtnIntent);
}
});
WebView browser = (WebView)findViewById(R.id.Adminloginwebview);
browser.setWebViewClient(new WebViewClient());
browser.loadUrl("http://sivasphpmobileapps.site90.net/NotificationBoard/NewEvents.php");
}
}
}

Flurry clips (video ads) integration for Android

Is it possible to integrate video ads from Flurry in an android app? I tried some things, but it didn't work. The Flurry Android SDK has the onVideoCompleted function, and in the Android Flurry SDK Release Notes, the following can be found: verified support for clips in AdUnity (http://support.flurry.com/index.php?title=Analytics/Code/ReleaseNotes/Android).
I tried this code, but it didn't work for me:
package com.test.flurrytest;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import com.flurry.android.FlurryAdType;
import com.flurry.android.FlurryAds;
import com.flurry.android.FlurryAdSize;
import com.flurry.android.FlurryAgent;
import com.flurry.android.FlurryAdListener;
public class MainActivity extends Activity implements AdCallbackListener, FlurryAdListener {
FrameLayout mBanner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mBanner = new FrameLayout(this);
FlurryAds.setAdListener(this);
FlurryAds.enableTestAds(true);
Button watchvideo = (Button) findViewById(R.id.watchvideo);
watchvideo.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
FlurryAds.fetchAd(MainActivity.this, "TestAdspace", mBanner, FlurryAdSize.FULLSCREEN);
FlurryAds.displayAd(MainActivity.this, "TestAdspace", mBanner);
}
});
}
// Flurry
#Override
public void onStart() {
super.onStart();
FlurryAgent.onStartSession(this, "****");
}
public void spaceDidReceiveAd(String adSpace) {
FlurryAds.displayAd(this, adSpace, mBanner);
}
public void onVideoCompleted(String adSpace) {
// The user get some points now
}
public boolean shouldDisplayAd(String adSpaceName, FlurryAdType type) {
return true;
}
public void onAdClosed(String adSpaceName) {
}
public void onRenderFailed(String adSpaceName) {
Toast.makeText(getApplicationContext(), "The video has failed to render. Try again.", Toast.LENGTH_LONG).show();
}
public void onApplicationExit(String adSpaceName) {
}
public void spaceDidFailToReceiveAd(String adSpaceName) {
Toast.makeText(getApplicationContext(), "Failed to receive ad. Try again.", Toast.LENGTH_LONG).show();
}
public void onAdClicked(String adSpaceName) {
}
public void onAdOpened(String adSpaceName) {
}
#Override
public void onStop() {
super.onStop();
FlurryAds.removeAd(this, "TestAdspace", mBanner);
FlurryAgent.onEndSession(this);
}
}
Is it possible with Android, and if so, how to integrate it?
Thanks!

Categories

Resources