How to capture MVXTrace in error reporting tool - xamarin

I'm using MvvmCross and playing around with some ways to get the MvxTrace in my reporting tool. In this case I'm using Raygun. Raygun gives me the option of including additional messages to the error message that I want to throw, which is what I'm thinking I have to use to get this to happen. Basically I want to do something like this in the code:
var client = new RaygunClient();
var tags = new List<string> { "myTag" };
var customData = new Dictionary<int, string>() { {1, "**MVXTrace stuff here**"} };
client.Send(exception, tags, customData);
How can I hook this up? I'm getting confused when I'm looking at the Trace setup. I'm assuming I need to do something with my DebugTrace file that I'm using to inject. Right now it looks like this:
public class DebugTrace : IMvxTrace
{
public void Trace(MvxTraceLevel level, string tag, Func<string> message)
{
Debug.WriteLine(tag + ":" + level + ":" + message());
}
public void Trace(MvxTraceLevel level, string tag, string message)
{
Debug.WriteLine(tag + ":" + level + ":" + message);
}
public void Trace(MvxTraceLevel level, string tag, string message, params object[] args)
{
try
{
Debug.WriteLine(string.Format(tag + ":" + level + ":" + message, args));
}
catch (FormatException)
{
Trace(MvxTraceLevel.Error, tag, "Exception during trace of {0} {1} {2}", level, message);
}
}
}
Can I do something that hooks into the IMvxTrace logic to attach inner exceptions and etc to my RaygunClient? It's hard for me to see what is causing specific errors because if I leave it the way it is I get errors that look like this:
[MvxException: Failed to construct and initialize ViewModel for type MyProject.Core.ViewModels.SignatureViewModel from locator MvxDefaultViewModelLocator - check MvxTrace for more information]
Cirrious.MvvmCross.ViewModels.MvxViewModelLoader.LoadViewModel(Cirrious.MvvmCross.ViewModels.MvxViewModelRequest request, IMvxBundle savedState, IMvxViewModelLocator viewModelLocator):0
Cirrious.MvvmCross.ViewModels.MvxViewModelLoader.LoadViewModel(Cirrious.MvvmCross.ViewModels.MvxViewModelRequest request, IMvxBundle savedState):0
Cirrious.MvvmCross.Droid.Views.MvxAndroidViewsContainer.ViewModelFromRequest(Cirrious.MvvmCross.ViewModels.MvxViewModelRequest viewModelRequest, IMvxBundle savedState):0
Cirrious.MvvmCross.Droid.Views.MvxAndroidViewsContainer.CreateViewModelFromIntent(Android.Content.Intent intent, IMvxBundle savedState):0
Cirrious.MvvmCross.Droid.Views.MvxAndroidViewsContainer.Load(Android.Content.Intent intent, IMvxBundle savedState, System.Type viewModelTypeHint):0
Cirrious.MvvmCross.Droid.Views.MvxActivityViewExtensions.LoadViewModel(IMvxAndroidView androidView, IMvxBundle savedState):0
Cirrious.MvvmCross.Droid.Views.MvxActivityViewExtensions+<>c__DisplayClass3.<OnViewCreate>b__1():0
Cirrious.MvvmCross.Views.MvxViewExtensionMethods.OnViewCreate(IMvxView view, System.Func`1 viewModelLoader):0
Cirrious.MvvmCross.Droid.Views.MvxActivityViewExtensions.OnViewCreate(IMvxAndroidView androidView, Android.OS.Bundle bundle):0
Cirrious.MvvmCross.Droid.Views.MvxActivityAdapter.EventSourceOnCreateCalled(System.Object sender, Cirrious.CrossCore.Core.MvxValueEventArgs`1 eventArgs):0
(wrapper delegate-invoke) System.EventHandler`1<Cirrious.CrossCore.Core.MvxValueEventArgs`1<Android.OS.Bundle>>:invoke_void__this___object_TEventArgs (object,Cirrious.CrossCore.Core.MvxValueEventArgs`1<Android.OS.Bundle>)
Cirrious.CrossCore.Core.MvxDelegateExtensionMethods.Raise[Bundle](System.EventHandler`1 eventHandler, System.Object sender, Android.OS.Bundle value):0
Cirrious.CrossCore.Droid.Views.MvxEventSourceActivity.OnCreate(Android.OS.Bundle bundle):0
MyProject.Droid.Views.SignatureView.OnCreate(Android.OS.Bundle bundle):0
Android.App.Activity.n_OnCreate_Landroid_os_Bundle_(IntPtr jnienv, IntPtr native__this, IntPtr native_savedInstanceState):0
(wrapper dynamic-method) object:3af7783d-a44d-471c-84a6-662ebfaea4ae (intptr,intptr,intptr)
It would be really helpful, as that message suggests, if I could get the MvxTrace with it to track down exactly why initializing this ViewModel failed. Any suggestions?

This is how I do it on Android. I use the Android.Util.Log class. This will then log the messages to the Android Device Log.
public class DebugTrace : IMvxTrace
{
public void Trace(MvxTraceLevel level, string tag, Func<string> message)
{
Trace(level, tag, message());
}
public void Trace(MvxTraceLevel level, string tag, string message)
{
switch (level)
{
case MvxTraceLevel.Diagnostic:
Log.Debug(tag, message);
break;
case MvxTraceLevel.Warning:
Log.Warn(tag, message);
break;
case MvxTraceLevel.Error:
Log.Error(tag, message);
break;
default:
Log.Info(tag, message);
break;
}
}
public void Trace(MvxTraceLevel level, string tag, string message, params object[] args)
{
try
{
Trace(level, tag, string.Format(message, args));
}
catch (FormatException)
{
Trace(MvxTraceLevel.Error, tag, "Exception during trace of {0} {1}", level, message);
}
}
}
You can then get the log using the following:
public class AndroidLogReader
{
public string ReadLog(string tag)
{
var cmd = "logcat -d";
if (!string.IsNullOrEmpty(tag)) cmd += " -s " + tag;
var process = Java.Lang.Runtime.GetRuntime().Exec(cmd);
using (var sr = new StreamReader(process.InputStream))
{
return sr.ReadToEnd();
}
}
}

Here is what I did to get this to work for me:
I have a BaseView that I'm using for all of my Android activities. I make use of this BaseView to hook up and log Unhandled Exceptions like so:
public abstract class BaseView : MvxActivity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
AppDomain.CurrentDomain.UnhandledException += HandleUnhandledException;
AndroidEnvironment.UnhandledExceptionRaiser += HandleAndroidException;
}
protected void HandleUnhandledException(object sender, UnhandledExceptionEventArgs args)
{
var e = (Exception)args.ExceptionObject;
Mvx.Trace(MvxTraceLevel.Error, "Exception: {0}", e.ToLongString());
var logReader = new AndroidLogReader();
var logMessages = logReader.ReadLog("mvx:E");
var customData = new Dictionary<string, string> { { "logMessage", logMessages } };
var session = SessionController.Instance;
var user = new RaygunIdentifierMessage(session.UserName + " " + session.Company);
var rayMessage = RaygunMessageBuilder.New
.SetEnvironmentDetails()
.SetMachineName(Environment.MachineName)
.SetClientDetails()
.SetExceptionDetails(e)
.SetUser(user)
.SetUserCustomData(customData)
.Build();
RaygunClient.Current.Send(rayMessage);
}
protected void HandleAndroidException(object sender, RaiseThrowableEventArgs e)
{
var exception = e.Exception;
Mvx.Trace(MvxTraceLevel.Error, "Exception: {0}", e.Exception.ToLongString());
var logReader = new AndroidLogReader();
var logMessages = logReader.ReadLog("mvx:E");
var customData = new Dictionary<string, string> { { "logMessage", logMessages } };
var session = SessionController.Instance;
var user = new RaygunIdentifierMessage(session.UserName + " " + session.Company);
var rayMessage = RaygunMessageBuilder.New
.SetEnvironmentDetails()
.SetMachineName(Environment.MachineName)
.SetClientDetails()
.SetExceptionDetails(exception)
.SetUser(user)
.SetUserCustomData(customData)
.Build();
RaygunClient.Current.Send(rayMessage);
}
}
My DebugTrace.cs looks like so:
public class DebugTrace : IMvxTrace
{
public void Trace(MvxTraceLevel level, string tag, Func<string> message)
{
Trace(level, tag, message());
}
public void Trace(MvxTraceLevel level, string tag, string message)
{
switch (level)
{
case MvxTraceLevel.Diagnostic:
Log.Debug(tag, message);
break;
case MvxTraceLevel.Warning:
Log.Warn(tag, message);
break;
case MvxTraceLevel.Error:
Log.Error(tag, message);
break;
default:
Log.Info(tag, message);
break;
}
}
public void Trace(MvxTraceLevel level, string tag, string message, params object[] args)
{
try
{
Trace(level, tag, string.Format(message, args));
}
catch (FormatException)
{
Trace(MvxTraceLevel.Error, tag, "Exception during trace of {0} {1} {2}", level, message);
}
}
}
And my AndroidLogReader looks like so:
public class AndroidLogReader
{
public string ReadLog(string tag)
{
var cmd = "logcat -d";
if (!string.IsNullOrEmpty(tag))
{
cmd += " -s " + tag;
}
var process = Java.Lang.Runtime.GetRuntime().Exec(cmd);
using (var sr = new StreamReader(process.InputStream))
{
return sr.ReadToEnd();
}
}
}
With these things in place I now get custom data attached to all of my Raygun errors that includes the stack trace for all errors from Mvx. Thank you so much #Kiliman for pointing me towards the building blocks to get this to work!

Related

xposed hook all method of ViewGroup crash

I want to hook all method of ViewGroup, so write below code:
final Class<?> mViewGroup = XposedHelpers.findClass("android.view.ViewGroup", lpparam.classLoader);
for (final Method method : mViewGroup.getDeclaredMethods()) {
if (true == Modifier.isAbstract(method.getModifiers())){
XposedBridge.log("skip abstract:" + method.getName());
continue;
}
XposedBridge.log("----" + method.getName());
XposedBridge.hookMethod(method, methodHook);
}
final StringBuilder sb = new StringBuilder();
XC_MethodHook methodHook = new XC_MethodHook() {
#Override
protected void beforeHookedMethod(XC_MethodHook.MethodHookParam param) throws Throwable {
dumpParams(param);
}
#Override
protected void afterHookedMethod(XC_MethodHook.MethodHookParam param) throws Throwable {
//param.setResult(false);
XposedBridge.log("after:" + param.getResult());
}
};
private void dumpParams(XC_MethodHook.MethodHookParam param) {
sb.setLength(0);
sb.append(param.method.getName()).append("(");
for (Object o:param.args) {
String typnam = "";
String value = "null";
if (o != null) {
typnam = o.getClass().getName();
value = o.toString();
}
sb.append(typnam).append(":").append(value).append(", ");
}
XposedBridge.log(sb.toString());
}
But when I run it, hook class sounds fine, but when execute it crashed at android.view.View$AttachInfo:
am_crash: `java.lang.IllegalAccessError,Illegal class access: 'EdHooker45' attempting to access 'android.view.View$AttachInfo' (declaration of 'EdHooker45' appears in /data/user_de/0/.../1129433416.jar),NULL,120]`

JSON Array With Volley Showing Only One data

I am trying to display array data using JSON Volley in PostsBasedOnCategory.java. Array data that I want to display are, Title post, and excerpt based on specific category from https://www.kisahmuslim.com/wp-json/wp/v2/categories. But unfortunately, it only showing one result.
Below you can check my code
DaftarCategories.java
public class CallingPage extends AsyncTask<String, String, String> {
HttpURLConnection conn;
java.net.URL url = null;
private int page = 1;
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
showNoFav(false);
pb.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... params) {
try {
url = new URL("https://www.kisahmuslim.com/wp-json/wp/v2/categories");
}
catch(MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return("koneksi gagal");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
protected void onPostExecute(String result)
{
JsonArrayRequest stringRequest = new JsonArrayRequest(Request.Method.GET, SumberPosts.HOST_URL+"wp/v2/categories/", null, new Response.Listener<JSONArray>()
{
#Override
public void onResponse(JSONArray response) {
// display response
Log.d(TAG, response.toString() + "Size: "+response.length());
// agar setiap kali direfresh data tidak redundant
typeForPosts.clear();
for(int i=0; i<response.length(); i++) { //ambil semua objek yang ada
final CategoriesModel post = new CategoriesModel();
try {
Log.d(TAG, "Object at " + i + response.get(i));
JSONObject obj = response.getJSONObject(i);
post.setId(obj.getInt("id"));
post.setPostURL(obj.getString("link"));
//Get category name
post.setCategory(obj.getString("name"));
//////////////////////////////////////////////////////////////////////////////////////
// getting article konten
JSONObject postCategoryParent = obj.getJSONObject("_links");
JSONArray postCategoryObj = postCategoryParent.getJSONArray("wp:post_type");
JSONObject postCategoryIndex = postCategoryObj.getJSONObject(0); //ambil satu objek saja
String postCategoryUrl = postCategoryIndex.getString("href"); //satu objek yang dimaksud adalah href
if(postCategoryUrl != null) {
Log.d(TAG, postCategoryIndex.getString("href"));
JsonArrayRequest getKonten = new JsonArrayRequest(Request.Method.GET, postCategoryUrl, null, new Response.Listener<JSONArray>()
{
#Override
public void onResponse(JSONArray respon) {
Log.d(TAG, respon.toString() + "Size: "+respon.length());
for(int d=0; d<respon.length(); d++) {
try {
//Log.d(TAG, "Object at " + i + respon.get());
JSONObject objek = respon.getJSONObject(d); //ambil semua artikel yang tersedia di postCategoryUrl
post.setId(objek.getInt("id"));
post.setCreatedAt(objek.getString("date"));
post.setPostURL(objek.getString("link"));
//Get category title
JSONObject titleObj = objek.getJSONObject("title");
post.setJudul(titleObj.getString("rendered"));
//Get excerpt
JSONObject exerptObj = objek.getJSONObject("excerpt");
post.setExcerpt(exerptObj.getString("rendered"));
// Get content
JSONObject contentObj = objek.getJSONObject("content");
post.setContent(contentObj.getString("rendered"));
}
catch (JSONException e) {
e.printStackTrace();
}
}// for category
} //onResponse2
}, new Response.ErrorListener() { //getKonten
#Override
public void onErrorResponse(VolleyError error) {
pb.setVisibility(View.GONE);
Log.d(TAG, error.toString());
}
});
queue.add(getKonten);
} //if postCategoryUrl
//////////////////////////////////////////////////////////////////////////////////////
typeForPosts.add(post);
} //try 1
catch (JSONException e) {
e.printStackTrace();
}
} //for 1
pb.setVisibility(View.GONE);
recycleViewWordPress.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
} //onResponse1
}, new Response.ErrorListener() { //stringRequest
#Override
public void onErrorResponse(VolleyError error) {
showNoFav(true);
pb.setVisibility(View.GONE);
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getContext(), "Tidak bisa menampilkan data. Periksa kembali sambungan internet Anda", Toast.LENGTH_LONG).show();
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
} //onPostExecute
} //CallingPage
#Override
public void onPostingSelected(int pos) {
CategoriesModel click = typeForPosts.get(pos);
excerpt = click.getExcerpt();
//gambar = click.getPostImg();
judul = click.getJudul();
//url = click.getPostURL();
content = click.getContent();
Bundle bundle = new Bundle();
bundle.putString("judul", judul);
//bundle.putString("gambar", gambar);
//bundle.putString("url", url);
bundle.putString("content", content);
bundle.putString("excerpt", excerpt);
PostsBasedOnCategory bookFragment = new PostsBasedOnCategory();
bookFragment.setArguments(bundle);
AppCompatActivity activity = (AppCompatActivity) getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.flContainerFragment, bookFragment).addToBackStack(null).commit();
}
PostsBasedOnCategory.java
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_wordpress, container,false);
ButterKnife.bind(this,view);
setHasOptionsMenu(true);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
swipeRefreshLayout =(SwipeRefreshLayout) getActivity().findViewById(R.id.swipeRefreshLayout);
recycleViewWordPress =(RecyclerView) getActivity().findViewById(R.id.recycleViewWordPress);
pb = (ProgressBar) getActivity().findViewById(R.id.loadingPanel);
noFavtsTV = getActivity().findViewById(R.id.no_favt_text);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(false);
pb.setVisibility(View.VISIBLE);
recycleViewWordPress.setAdapter(mAdapter);
}
});
typeForPosts = new ArrayList<CategoriesModel>();
recycleViewWordPress.setHasFixedSize(true);
recycleViewWordPress.setLayoutManager(new LinearLayoutManager(getContext()));
recycleViewWordPress.setNestedScrollingEnabled(false);
mAdapter = new AdapterCategoryPosts(getContext(), typeForPosts, this);
recycleViewWordPress.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
loadData();
}
public void loadData() {
Bundle bundel = this.getArguments();
long id = bundel.getLong("id");
String kategori = bundel.getString("kategori");
String title = bundel.getString("judul");
String excerpt = bundel.getString("excerpt");
String pict = bundel.getString("gambar");
String url = bundel.getString("url");
String konten = bundel.getString("konten");
CategoriesModel list = new CategoriesModel();
list.setId(id);
list.setCategory(kategori);
list.setJudul(title);
list.setExcerpt(excerpt);
list.setPostImg(pict);
list.setPostURL(url);
list.setContent(konten);
typeForPosts.add(list);
}
Logcat
2019-09-07 12:01:27.941 11246-11246/com.kursusarabic.arabicforfun D/postFrag: [{"id":12,"count":53,"description":"","link":"https:\/\/kisahmuslim.com\/category\/kisah-nyata\/biografi-ulama","name":"Biografi Ulama","slug":"biografi-ulama","taxonomy":"category","parent":29,"meta":[],"_links":{"self":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/12"}],"collection":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories"}],"about":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/taxonomies\/category"}],"up":[{"embeddable":true,"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/29"}],"wp:post_type":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/posts?categories=12"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}},{"id":26,"count":8,"description":"","link":"https:\/\/kisahmuslim.com\/category\/download","name":"Download","slug":"download","taxonomy":"category","parent":0,"meta":[],"_links":{"self":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/26"}],"collection":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories"}],"about":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/taxonomies\/category"}],"wp:post_type":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/posts?categories=26"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}},{"id":1812,"count":9,"description":"","link":"https:\/\/kisahmuslim.com\/category\/info","name":"Info","slug":"info","taxonomy":"category","parent":0,"meta":[],"_links":{"self":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/1812"}],"collection":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories"}],"about":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/taxonomies\/category"}],"wp:post_type":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/posts?categories=1812"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}},{"id":17,"count":3,"description":"","link":"https:\/\/kisahmuslim.com\/category\/kisah-nyata\/kisah-birrul-walidain","name":"Kisah Birrul Walidain","slug":"kisah-birrul-walidain","taxonomy":"category","parent":29,"meta":[],"_links":{"self":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/17"}],"collection":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories"}],"about":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/taxonomies\/category"}],"up":[{"embeddable":true,"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/29"}],"wp:post_type":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/posts?categories=17"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}},{"id":25,"count":31,"description":"","link":"https:\/\/kisahmuslim.com\/category\/kisah-nyata\/kisah-hidayah-islam","name":"Kisah Hidayah Islam","slug":"kisah-hidayah-islam","taxonomy":"category","parent":29,"meta":[],"_links":{"self":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/25"}],"collection":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories"}],"about":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/taxonomies\/category"}],"up":[{"embeddable":true,"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/29"}],"wp:post_type":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/posts?categories=25"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}},{"id":16,"count":49,"description":"","link":"https:\/\/kisahmuslim.com\/category\/kisah-nyata\/kisah-kaum-durhaka","name":"Kisah Kaum Durhaka","slug":"kisah-kaum-durhaka","taxonomy":"category","parent":29,"meta":[],"_links":{"self":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/16"}],"collection":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories"}],"about":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/taxonomies\/category"}],"up":[{"embeddable":true,"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/29"}],"wp:post_type":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/posts?categories=1
2019-09-07 12:01:27.942 11246-11246/com.kursusarabic.arabicforfun D/postFrag: Object at 0{"id":12,"count":53,"description":"","link":"https:\/\/kisahmuslim.com\/category\/kisah-nyata\/biografi-ulama","name":"Biografi Ulama","slug":"biografi-ulama","taxonomy":"category","parent":29,"meta":[],"_links":{"self":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/12"}],"collection":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories"}],"about":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/taxonomies\/category"}],"up":[{"embeddable":true,"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/29"}],"wp:post_type":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/posts?categories=12"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}
2019-09-07 12:01:27.942 11246-11246/com.kursusarabic.arabicforfun D/postFrag: https://kisahmuslim.com/wp-json/wp/v2/posts?categories=12
You cannot call network requests in loop, Use async processing or
Retrofit & RxJava multiple requests complete
and after updating typeForPosts, there is no need to setAdapter on recyclerview just call adapter.notifyDataSetChanged()

How to get a list of all the headers for logging in web api

I want to log all the request headers. I already have a filter like so.
Now how do I get all the request header so that I can log them?
public class LogApiFilter : AbstractActionFilter
{
private readonly ILog m_Log;
public override bool AllowMultiple
{
get
{
return true;
}
}
public LogApiFilter(ILog iLog)
{
if (iLog == null)
throw new ArgumentNullException("log instance injected is null.");
m_Log = iLog;
}
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
base.OnActionExecuted(actionExecutedContext);
}
public override void OnActionExecuting(HttpActionContext context)
{
m_Log.Debug("Web api Controller Name and Action method Name: "
+ context.ActionDescriptor.ControllerDescriptor.ControllerName
+ ", " + context.ActionDescriptor.ActionName);
base.OnActionExecuting(context);
}
}
Ok, for my own records and for others, I have comeup with this. Please do suggest if there is a better way.
private string GetRequestHeaders(HttpActionContext context)
{
// Note you can replace the type names sucha as string, HttpRequestHeaders, List<KeyValuePair<string, IEnumerable<string>>>
// with var keyword where ever possible for readability.
string headerString = string.Empty;
HttpRequestHeaders requestHeaders = context.Request.Headers;
List<KeyValuePair<string, IEnumerable<string>>> headerList = requestHeaders.ToList();
foreach (var header in headerList)
{
string key = header.Key;
List<string> valueList = header.Value.ToList();
string valueString = string.Empty;
foreach (var v in valueList)
{
valueString = valueString + v + "-";
}
headerString = headerString + key + ": " + valueString + Environment.NewLine;
}
return headerString;
}
The above method can be called from the action filter in the question. I am calling it from the method, OnActionExecuting(HttpActionContext context).
I am using ninject for di, so this is how I have configured it.
kernel.BindHttpFilter<LogApiFilter>(System.Web.Http.Filters.FilterScope.Global);
kernel.BindHttpFilter<ApiExceptionFilterAttribute>(System.Web.Http.Filters.FilterScope.Global);
kernel.BindFilter<LogMvcFilter>(System.Web.Mvc.FilterScope.Global, 0);

Finish activity when onPostExecute is called (in AsyncTask)

I use the GMS Drive sample demo.
I want to select a file (with Drive dialog open file), download the file, then finish the activity.
My problem is if I use finish() in the onActivityResult, I cannot get the result in my main activity, if I use finish() in the onPostExecute, the dialog is not closed, and I need to press "Cancel" to return to my main activity (with the result). I would like to return without pressing "cancel" button...
I use the RetrieveContentsActivity and PickFileWithOpenerActivity from the demo.
Here is my code :
public class RestoreActivity extends DriveActivity {
private static final int REQUEST_CODE_OPENER = 1;
#Override
public void onConnected(Bundle connectionHint) {
super.onConnected(connectionHint);
IntentSender intentSender = Drive.DriveApi
.newOpenFileActivityBuilder()
.setSelectionFilter(Filters.contains(SearchableField.TITLE, "settings"))
.build(getGoogleApiClient());
try {
startIntentSenderForResult(intentSender, REQUEST_CODE_OPENER, null, 0, 0, 0);
} catch (IntentSender.SendIntentException e) {
Log.w(TAG, "Unable to send intent", e);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CODE_OPENER:
if (resultCode == RESULT_OK) {
DriveId driveId = data.getParcelableExtra(OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
new RetrieveDriveFileContentsAsyncTask(RestoreActivity.this).execute(driveId);
}
finish(); // if I put finish() here, I cannot get the result in onActivityResult (main activity)
break;
default:
super.onActivityResult(requestCode, resultCode, data);
}
}
final private class RetrieveDriveFileContentsAsyncTask extends ApiClientAsyncTask<DriveId, Boolean, String> {
public RetrieveDriveFileContentsAsyncTask(Context context) {
super(context);
}
#Override
protected String doInBackgroundConnected(DriveId... params) {
String contents = null;
DriveFile file = Drive.DriveApi.getFile(getGoogleApiClient(), params[0]);
DriveApi.DriveContentsResult driveContentsResult = file.open(getGoogleApiClient(), DriveFile.MODE_READ_ONLY, null).await();
if (!driveContentsResult.getStatus().isSuccess()) {
return null;
}
DriveContents driveContents = driveContentsResult.getDriveContents();
BufferedReader reader = new BufferedReader(
new InputStreamReader(driveContents.getInputStream()));
StringBuilder builder = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
builder.append(line);
}
contents = builder.toString();
} catch (IOException e) {
Log.e(TAG, "IOException while reading from the stream " + e.toString());
}
driveContents.discard(getGoogleApiClient());
return contents;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Intent returnIntent = new Intent();
returnIntent.putExtra("settings",result);
if (result == null) {
Log.w(TAG, "Error");
setResult(RESULT_CANCELED,returnIntent);
} else {
Log.i(TAG, "OK");
setResult(RESULT_OK,returnIntent);
}
// if I put finish() here nothing happens, and dialog is still opened till I press "Cancel" button
}
}
}
How can I return to the main activity after onPostExecute and stop intent DriveApi ?
Thanks
I found a solution that I don't like : make it in 2 steps.
pick the file using the PickFileActivity from demo, return the driveId by declaring it public in MainActivity (public static DriveId driveId) and changing code like this :
MainActivity.driveId = data.getParcelableExtra(OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
move the AsyncTask in my MainActivity.
If someone find another solution ?

java.lang.NullPointerException in textview inside asyncTask

If I use the following code, I will have no error, but there will be a freeze time.
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.profilepic);
initialize();
Bundle bundle = getIntent().getExtras();
email = bundle.getString("Email");
ArrayList<NameValuePair> postParameters;
String response = null;
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("emaillog", email));
try {
response = CustomHttpClient.executeHttpPost("http://whatstherex.info/checkU.php", postParameters);
res = response.toString();
res = res.replaceAll("null", "");
username = res.toString();
tvProfilePic.setText("Hi " + username + ", you are encourage to add a profile picture.");
}catch(Exception e){
res = e.toString();
tvProfilePic.setText(res);
}
}
But if I use this code with asyncTask and progressDialog like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.profilepic);
initialize();
getUsername();
}
private AsyncTask<String, Void, String> task;
public void getUsername(){
Bundle bundle = getIntent().getExtras();
email = bundle.getString("Email");
task = new AsyncTask<String, Void, String>() {
ProgressDialog dialog;
ArrayList<NameValuePair> postParameters;
String response = null;
#Override
protected void onPreExecute() {
//
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("emaillog", email));
dialog = new ProgressDialog(Profilepic.this, ProgressDialog.STYLE_SPINNER);
dialog.setMessage("Loading Data...");
dialog.show();
}
#Override
protected String doInBackground(String... params) {
//
try {
response = CustomHttpClient.executeHttpPost("http://whatstherex.info/checkU.php", postParameters);
res = response.toString();
res = res.replaceAll("null", "");
username = res.toString();
return username;
}catch(Exception e){
res = e.toString();
return res;
}
}
#Override
protected void onPostExecute(String result) {
if(result.length()< 25){
username = result;
tvProfilePic.setText("Hi " + result + ", you are encourage to add a profile picture.");
dialog.dismiss();
}else{
tvProfilePic.setText(result);
dialog.dismiss();
}
}
};
task.execute();
}
I get java.lang.NullPointerException in the textview.
What's the problem? Can anyone help me how to resolve this issue with NullPointerException appearing?
I see that you use tvProfilePic but I don't see where you define it.
In case you are not defining it, it should be done in a similar way as
tvProfilePic = findViewById(R.id.profile_pic)
Are you doing this?
Note that 'profile_pic' is the name in the layout XML document.
You are using tvProfilePic as a textview but i can't see where you defined it.
if you are not defining it then define it using something like
tvProfilePic = findViewById(R.id.profile_pic)
You are getting nullpointerexception because your tvProfilePic is null

Resources