App runs fine on avd but not on actual device - javascript

I'm kind of new to android, actually this is my first app. The app is not completed through, i wanted to test the UI, it works fine on AVD, but when I copy the .apk file from bin folder to my phone, it installs fine, but wont work ends up with force close error. I have no idea what's the problem, I saw on other post about parsing the content in edittext, i took out the layout and ran it again still not working. again, I am new to this, please help me.
Mainactivity.java
package com.example.studentapp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import com.example.studentapp.ExpandableListAdapter;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
DrawerLayout mDrawerLayout;
ExpandableListView mDrawerList;
ExpandableListAdapter listAdapter;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
private ActionBarDrawerToggle actionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getfragment(125);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ExpandableListView) findViewById(R.id.left_drawer);
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
// setting list adapter
mDrawerList.setAdapter(listAdapter);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
);
// 2.2 Set actionBarDrawerToggle as the DrawerListener
mDrawerLayout.setDrawerListener(actionBarDrawerToggle);
// 2.3 enable and show "up" arrow
getActionBar().setDisplayHomeAsUpEnabled(true);
// Listview Group click listener
mDrawerList.setOnGroupClickListener(new OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
Toast.makeText(getApplicationContext(),
"Group Clicked " + (groupPosition),
Toast.LENGTH_SHORT).show();
//return true for non collapsable items, and false for collapsable items.
if(groupPosition==1 || groupPosition==2)
{ // getfragment(groupPosition);
getActionBar().setTitle(listDataHeader.get(groupPosition));
return true;}
else
return false;
}
});
// Listview Group expanded listener
mDrawerList.setOnGroupExpandListener(new OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " Expanded",
Toast.LENGTH_SHORT).show();
}
});
// Listview Group collasped listener
mDrawerList.setOnGroupCollapseListener(new OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " Collapsed",
Toast.LENGTH_SHORT).show();
}
});
// Listview on child click listener
mDrawerList.setOnChildClickListener(new OnChildClickListener() {
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// TODO Auto-generated method stub
Toast.makeText(
getApplicationContext(),
listDataHeader.get(groupPosition)
+ " : "
+ listDataChild.get(
listDataHeader.get(groupPosition)).get(
childPosition), Toast.LENGTH_SHORT)
.show();
getActionBar().setTitle(listDataChild.get(
listDataHeader.get(groupPosition)).get(
childPosition));
return false;
}
});
}
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
actionBarDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// call ActionBarDrawerToggle.onOptionsItemSelected(), if it returns true
// then it has handled the app icon touch event
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding header data
listDataHeader.add("Center Details");
// Adding child data
List<String> CentDet = new ArrayList<String>();
CentDet.add("Study Center");
CentDet.add("Information Center");
CentDet.add("Overseas Center");
listDataHeader.add("Login");
listDataHeader.add("PCP Schedule");
listDataHeader.add("Course");
List<String> courseS = new ArrayList<String>();
courseS.add("Study Materials");
courseS.add("Syllabus");
listDataHeader.add("Exam");
List<String> Exams = new ArrayList<String>();
Exams.add("Hall Ticket");
Exams.add("Exam Venue");
Exams.add("Exam Schedule");
Exams.add("Practical Schedule");
Exams.add("Model Question Papers");
listDataHeader.add("Results");
List<String> Resultss= new ArrayList<String>();
Resultss.add("Regular Stream");
Resultss.add("Overseas");
listDataChild.put(listDataHeader.get(0), CentDet); // Header, Child data
listDataChild.put(listDataHeader.get(1), null);
listDataChild.put(listDataHeader.get(2), null);
listDataChild.put(listDataHeader.get(3), courseS);
listDataChild.put(listDataHeader.get(4), Exams);
listDataChild.put(listDataHeader.get(5), Resultss);
}
void getfragment(int x)
{
android.app.FragmentManager fragmentManager1 = getFragmentManager();
android.app.FragmentTransaction fragmentTransaction1 = fragmentManager1.beginTransaction();
fragmenttwo lm_fragment = new fragmenttwo();
switch (x)
{
// case 1:
// lm_fragment.fragmenttwoo(1);
//
//break;
case 2:
lm_fragment.fragmenttwoo(2);
break;
case 3:
lm_fragment.fragmenttwoo(3);
break;
case 125:
lm_fragment.fragmenttwoo(125);
break;
}
fragmentTransaction1.replace(R.id.content_frame, lm_fragment);
fragmentTransaction1.commit();
}
}
fragmenttwo.java
package com.example.studentapp;
import android.annotation.TargetApi;
import android.app.Fragment;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class fragmenttwo extends Fragment{
public int x;
public fragmenttwo(){}
public void fragmenttwoo(int n)
{
switch(n)
{
case 125:
x = com.example.studentapp.R.layout.sample;
break;
// case 1:
// x = com.example.studentapp.R.layout.login;
// break;
case 2:
x = com.example.studentapp.R.layout.pcpschedule;
break;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
/** * Inflate the layout for this fragment */
// switch(x)
// {
// int idno= r.layout.layoutu want for each case
//put the idno on below as parameter instead of r.layout.sample
//}
return inflater.inflate( x, container, false);
}
}
ExpandableListAdpater.java
package com.example.studentapp;
import java.util.HashMap;
import java.util.List;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
public ExpandableListAdapter(Context context, List<String> listDataHeader,
HashMap<String, List<String>> listChildData) {
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
}
TextView txtListChild = (TextView) convertView
.findViewById(R.id.lblListItem);
txtListChild.setText(childText);
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.size();
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount() {
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
any help would be appreciated.
As suggested i used adb and here is the logcat log, it says virtual method getfragment cannot be resolved...
06-03 21:18:03.789: W/dalvikvm(11126): VFY: unable to resolve virtual method 8281: Lcom/example/studentapp/MainActivity;.getFragmentManager ()Landroid/app/FragmentManager;
06-03 21:18:03.789: D/dalvikvm(11126): VFY: replacing opcode 0x6e at 0x0000
06-03 21:18:03.789: D/dalvikvm(11126): VFY: dead code 0x0003-0029 in Lcom/example/studentapp/MainActivity;.getfragment (I)V
06-03 21:18:03.812: W/dalvikvm(11126): VFY: unable to resolve virtual method 8279: Lcom/example/studentapp/MainActivity;.getActionBar ()Landroid/app/ActionBar;
06-03 21:18:03.812: D/dalvikvm(11126): VFY: replacing opcode 0x6e at 0x005b
06-03 21:18:03.812: D/dalvikvm(11126): VFY: dead code 0x005e-008b in Lcom/example/studentapp/MainActivity;.onCreate (Landroid/os/Bundle;)V
06-03 21:18:03.820: I/ApplicationPackageManager(11126): cscCountry is not German : INS
06-03 21:18:03.976: D/AndroidRuntime(11126): Shutting down VM
06-03 21:18:03.976: W/dalvikvm(11126): threadid=1: thread exiting with uncaught exception (group=0x40018578)
06-03 21:18:03.976: E/AndroidRuntime(11126): FATAL EXCEPTION: main
06-03 21:18:03.976: E/AndroidRuntime(11126): java.lang.NoSuchMethodError: com.example.studentapp.MainActivity.getFragmentManager
06-03 21:18:03.976: E/AndroidRuntime(11126): at com.example.studentapp.MainActivity.getfragment(MainActivity.java:223)
06-03 21:18:03.976: E/AndroidRuntime(11126): at com.example.studentapp.MainActivity.onCreate(MainActivity.java:42)
06-03 21:18:03.976: E/AndroidRuntime(11126): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
06-03 21:18:03.976: E/AndroidRuntime(11126): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
06-03 21:18:03.976: E/AndroidRuntime(11126): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
06-03 21:18:03.976: E/AndroidRuntime(11126): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
06-03 21:18:03.976: E/AndroidRuntime(11126): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
06-03 21:18:03.976: E/AndroidRuntime(11126): at android.os.Handler.dispatchMessage(Handler.java:99)
06-03 21:18:03.976: E/AndroidRuntime(11126): at android.os.Looper.loop(Looper.java:130)
06-03 21:18:03.976: E/AndroidRuntime(11126): at android.app.ActivityThread.main(ActivityThread.java:3687)
06-03 21:18:03.976: E/AndroidRuntime(11126): at java.lang.reflect.Method.invokeNative(Native Method)
06-03 21:18:03.976: E/AndroidRuntime(11126): at java.lang.reflect.Method.invoke(Method.java:507)
06-03 21:18:03.976: E/AndroidRuntime(11126): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
06-03 21:18:03.976: E/AndroidRuntime(11126): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
06-03 21:18:03.976: E/AndroidRuntime(11126): at dalvik.system.NativeStart.main(Native Method)

Read the logcat: noSuchMethodError on line 223. Double click that line in the logcat and you will end up on line 223 of your MainActivity. Tell us the code.
CscCountry is not German?
Or you are running on a device that does not know getActionBar().

Related

Closing dialog inside shouldOverrideUrlLoading() or ignoring in project, when is custom url open

I am trying to auth google user in WebView, I found a good solution for these days, it works fine for google login, but I cannot disable dialog in other urls like (, sms: , smsto:)
Example Situation: User click on telephone number in my app, it will open the phone dial, but when he returns back.. there is a empty dialog window with close button, i use it for google login with JS.
How can i close this dialog message inside the shouldOverrideUrlLoading()? Or is there any better solution to not open other links in the dialog? How can i improve my code to solve my problem? Thank you guys!
package com.example.app;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslCertificate;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.URLUtil;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.lang.reflect.Field;
import java.security.cert.X509Certificate;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class MainActivity extends Activity {
private WebView mWebView;
private String userAgent;
private Context contextPop;
private WebView webViewPop;
private AlertDialog builder;
#Override
#SuppressLint("SetJavaScriptEnabled")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userAgent = System.getProperty("http.agent");
mWebView = findViewById(R.id.activity_main_webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setUseWideViewPort(true);
webSettings.setAppCacheEnabled(false);
webSettings.setAllowFileAccess(true);
webSettings.setAllowFileAccessFromFileURLs(true);
webSettings.setAllowUniversalAccessFromFileURLs(true);
webSettings.setUserAgentString(userAgent+ "com.example.app");
mWebView.clearCache(true);
// REMOTE RESOURCE
mWebView.loadUrl("https://example.eu/");
mWebView.setWebChromeClient(new CustomChromeClient());
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setSupportMultipleWindows(true);
contextPop = this.getApplicationContext();
// LOCAL RESOURCE
// mWebView.loadUrl("file:///android_asset/index.html");
}
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
final Context myApp = this;
class CustomChromeClient extends WebChromeClient {
#Override
public boolean onCreateWindow(WebView view, boolean isDialog,
boolean isUserGesture, Message resultMsg) {
webViewPop = new WebView(contextPop);
webViewPop.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
String host = Uri.parse(url).getHost();
if (url.startsWith("tel:") || url.startsWith("sms:") || url.startsWith("smsto:") || url.startsWith("mms:") || url.startsWith("mmsto:"))
{
webViewPop.destroy();
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse(url));
startActivity(intent);
return true;
}
//Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
//view.getContext().startActivity(intent);
return false;
}
});
// Enable Cookies
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
if (android.os.Build.VERSION.SDK_INT >= 21) {
cookieManager.setAcceptThirdPartyCookies(webViewPop, true);
cookieManager.setAcceptThirdPartyCookies(mWebView, true);
}
WebSettings popSettings = webViewPop.getSettings();
// WebView tweaks for popups
webViewPop.setVerticalScrollBarEnabled(false);
webViewPop.setHorizontalScrollBarEnabled(false);
popSettings.setJavaScriptEnabled(true);
popSettings.setSaveFormData(true);
popSettings.setEnableSmoothTransition(true);
// Set User Agent
popSettings.setUserAgentString(userAgent + "Your App Info/Version");
// to support content re-layout for redirects
popSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
// handle new popups
webViewPop.setWebChromeClient(new CustomChromeClient());
// set the WebView as the AlertDialog.Builder’s view
builder = new AlertDialog.Builder(MainActivity.this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT).create();
builder.setTitle("");
builder.setView(webViewPop);
builder.setButton("Close", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
webViewPop.destroy();
dialog.dismiss();
}
});
builder.show();
builder.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(webViewPop);
resultMsg.sendToTarget();
return true;
}
#Override
public void onCloseWindow(WebView window) {
//Toast.makeText(contextPop,"onCloseWindow called",Toast.LENGTH_SHORT).show();
try {
webViewPop.destroy();
} catch (Exception e) {
Log.d("Webview Destroy Error: ", e.getStackTrace().toString());
}
try {
builder.dismiss();
} catch (Exception e) {
Log.d("Builder Dismiss Error: ", e.getStackTrace().toString());
}
}
#Override
public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
new AlertDialog.Builder(myApp)
.setMessage(message)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
result.confirm();
}
})
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
result.cancel();
}
})
.setCancelable(false)
.create()
.show();
return true;
}
#Override
public boolean onJsAlert(WebView view, final String url, String message,
JsResult result) {
new AlertDialog.Builder(myApp)
.setMessage(message)
.setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
arg0.dismiss();
}
})
.setCancelable(false)
.show();
result.cancel();
return true;
}
}
}

Open Android app with Webview by pressing deeplink URL from notifications

Background:
* Full Stack developer training (recently finished studies).
* Am not very (putting it mildly) Java savvy.
for the past couple of days I've been trying to make the tapping on a OneSignal notification open the app according to the URL stored in the notification payload.
What did work was:
* If the app is showing on the screen and you press the notification it works fine and opens it accordingly.
It does ALMOST work in the way that if the app is in the background and you press the notification it either:
1. Launches the app but on the main page
OR
2. Doesn't launch the app but when you actively go back to the app it shows the correct content (according to the URL of the notification)
Following is the code:
Thank you!
package app.web.hodaya;
import com.onesignal.OSNotificationOpenResult;
import com.onesignal.OneSignal;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import org.json.JSONObject;
import static com.onesignal.OneSignal.sendTag;
import static com.onesignal.OneSignal.sendTags;
public class MainActivity extends AppCompatActivity {
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
WebView.setWebContentsDebuggingEnabled(true);
}
CalculateObject calcObject = new CalculateObject();
PassingStringThrough passString = new PassingStringThrough();
ExampleNotificationOpenedHandler notificationOpened = new ExampleNotificationOpenedHandler();
UpdateOneSignalSettingTags sendTag = new UpdateOneSignalSettingTags();
super.onCreate(savedInstanceState);
// OneSignal Initialization
OneSignal.startInit(this)
.inFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification)
.unsubscribeWhenNotificationsAreDisabled(true)
.setNotificationOpenedHandler(new ExampleNotificationOpenedHandler())
.init();
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("https://hodaya-app.firebaseapp.com/");
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.addJavascriptInterface(passString, "ob1");
try {
this.getSupportActionBar().hide();
} catch (NullPointerException e) {
}
}
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
class PassingStringThrough {
#JavascriptInterface
public void passString(
String m, String m1, String n, String n1, String e, String e1,
String name, String name1, String gender, String gender1) {
sendTag(m, m1);
sendTag(n, n1);
sendTag(e, e1);
sendTag(name, name1);
sendTag(gender, gender1);
/* alternatively*/
// tags.put(m, m1);
// tags.put(n, n1);
// tags.put(e, e1);
// OneSignal.sendTags(tags);
Log.d("settingsPassedCorrectly", "I just got executed!" + m + m1 + n + n1 + e + e1 + name + name1 + gender + gender1);
}
}
class ExampleNotificationOpenedHandler implements OneSignal.NotificationOpenedHandler {
#Override
public void notificationOpened(OSNotificationOpenResult result) {
Log.i("OSNotificationPayload", "result.notification.payload.toJSONObject().toString(): " + result.notification.payload.toJSONObject().toString());
JSONObject data = result.notification.payload.additionalData;
String customKey;
if (data != null) {
customKey = data.optString("tryli", null);
// if (customKey != null)
Log.i("DeepLinkToCustomkey", "customkey set with value: " + customKey);
WebView webView1;
// setContentView(R.layout.activity_main);
webView1 = findViewById(R.id.webView);
webView1.setWebViewClient(new WebViewClient());
webView1.loadUrl(customKey);
// WebView webView = null;
}

Android Wear app has stopped working in android studio emulator

I'm trying to run a code in my android studio emulator but after I run it, the emulator keeps showing "(App name) has stopped. Open app again".
This is an app to get accelerometer and gyro sensor data from Android wear.
I've checked the logcat and found this error in the process.
03-06 04:18:57.364 3189-3189/com.drejkim.androidwearmotionsensors E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.drejkim.androidwearmotionsensors, PID: 3189
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.hardware.Sensor.getStringType()' on a null object reference
at com.drejkim.androidwearmotionsensors.SensorFragment.onCreateView(SensorFragment.java:63)
at android.app.Fragment.performCreateView(Fragment.java:2353)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:995)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1171)
at android.app.BackStackRecord.run(BackStackRecord.java:816)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1578)
at android.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:563)
at android.support.wearable.view.FragmentGridPagerAdapter.finishUpdate(FragmentGridPagerAdapter.java:196)
at android.support.wearable.view.GridViewPager.populate(GridViewPager.java:1161)
at android.support.wearable.view.GridViewPager.populate(GridViewPager.java:1008)
at android.support.wearable.view.GridViewPager.onMeasure(GridViewPager.java:1322)
at android.view.View.measure(View.java:19857)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.view.View.measure(View.java:19857)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.support.wearable.view.WatchViewStub.onMeasure(WatchViewStub.java:136)
at android.view.View.measure(View.java:19857)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.view.View.measure(View.java:19857)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at com.android.internal.policy.DecorView.onMeasure(DecorView.java:690)
at android.view.View.measure(View.java:19857)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2275)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1366)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1675)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1254)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6338)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:874)
at android.view.Choreographer.doCallbacks(Choreographer.java:686)
at android.view.Choreographer.doFrame(Choreographer.java:621)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:860)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
And here're three of my java codes:
SensorFragments.java:
package com.drejkim.androidwearmotionsensors;
import android.app.Fragment;
import android.content.Context;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.FloatMath;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class SensorFragment extends Fragment implements SensorEventListener {
private static final float SHAKE_THRESHOLD = 1.1f;
private static final int SHAKE_WAIT_TIME_MS = 250;
private static final float ROTATION_THRESHOLD = 2.0f;
private static final int ROTATION_WAIT_TIME_MS = 100;
private View mView;
private TextView mTextTitle;
private TextView mTextValues;
private SensorManager mSensorManager;
private Sensor mSensor;
private int mSensorType;
private long mShakeTime = 0;
private long mRotationTime = 0;
public static SensorFragment newInstance(int sensorType) {
SensorFragment f = new SensorFragment();
// Supply sensorType as an argument
Bundle args = new Bundle();
args.putInt("sensorType", sensorType);
f.setArguments(args);
return f;
}
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if(args != null) {
mSensorType = args.getInt("sensorType");
}
mSensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(mSensorType);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.sensor, container, false);
mTextTitle = (TextView) mView.findViewById(R.id.text_title);
mTextTitle.setText(mSensor.getStringType());
mTextValues = (TextView) mView.findViewById(R.id.text_values);
return mView;
}
#Override
public void onResume() {
super.onResume();
mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
public void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
#Override
public void onSensorChanged(SensorEvent event) {
// If sensor is unreliable, then just return
if (event.accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE)
{
return;
}
mTextValues.setText(
"x = " + Float.toString(event.values[0]) + "\n" +
"y = " + Float.toString(event.values[1]) + "\n" +
"z = " + Float.toString(event.values[2]) + "\n"
);
if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
detectShake(event);
}
else if(event.sensor.getType() == Sensor.TYPE_GYROSCOPE) {
detectRotation(event);
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
// References:
// - http://jasonmcreynolds.com/?p=388
// - http://code.tutsplus.com/tutorials/using-the-accelerometer-on-android--mobile-22125
private void detectShake(SensorEvent event) {
long now = System.currentTimeMillis();
if((now - mShakeTime) > SHAKE_WAIT_TIME_MS) {
mShakeTime = now;
float gX = event.values[0] / SensorManager.GRAVITY_EARTH;
float gY = event.values[1] / SensorManager.GRAVITY_EARTH;
float gZ = event.values[2] / SensorManager.GRAVITY_EARTH;
// gForce will be close to 1 when there is no movement
float gForce = FloatMath.sqrt(gX*gX + gY*gY + gZ*gZ);
// Change background color if gForce exceeds threshold;
// otherwise, reset the color
if(gForce > SHAKE_THRESHOLD) {
mView.setBackgroundColor(Color.rgb(0, 100, 0));
}
else {
mView.setBackgroundColor(Color.BLACK);
}
}
}
private void detectRotation(SensorEvent event) {
long now = System.currentTimeMillis();
if((now - mRotationTime) > ROTATION_WAIT_TIME_MS) {
mRotationTime = now;
// Change background color if rate of rotation around any
// axis and in any direction exceeds threshold;
// otherwise, reset the color
if(Math.abs(event.values[0]) > ROTATION_THRESHOLD ||
Math.abs(event.values[1]) > ROTATION_THRESHOLD ||
Math.abs(event.values[2]) > ROTATION_THRESHOLD) {
mView.setBackgroundColor(Color.rgb(0, 100, 0));
}
else {
mView.setBackgroundColor(Color.BLACK);
}
}
}
}
MainActivity.Java:
package com.drejkim.androidwearmotionsensors;
import android.app.Activity;
import android.os.Bundle;
import android.support.wearable.view.DotsPageIndicator;
import android.support.wearable.view.GridViewPager;
import android.support.wearable.view.WatchViewStub;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
#Override public void onLayoutInflated(WatchViewStub stub) {
final GridViewPager pager = (GridViewPager) findViewById(R.id.pager);
pager.setAdapter(new SensorFragmentPagerAdapter(getFragmentManager()));
DotsPageIndicator indicator = (DotsPageIndicator) findViewById(R.id.page_indicator);
indicator.setPager(pager);
}
});
}
}
SensorFragmentPagerAdapter.java:
package com.drejkim.androidwearmotionsensors;
import android.app.Fragment;
import android.app.FragmentManager;
import android.hardware.Sensor;
import android.support.wearable.view.FragmentGridPagerAdapter;
public class SensorFragmentPagerAdapter extends FragmentGridPagerAdapter {
private int[] sensorTypes = {
Sensor.TYPE_ACCELEROMETER,
Sensor.TYPE_GYROSCOPE
};
public SensorFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getFragment(int row, int column) {
return SensorFragment.newInstance(sensorTypes[column]);
}
#Override
public int getRowCount() {
return 1; // fix to 1 row
}
#Override
public int getColumnCount(int row) {
return sensorTypes.length;
}
}
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.drejkim.androidwearmotionsensors" >
<uses-feature android:name="android.hardware.type.watch" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.DeviceDefault" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Can someone help me out? I got this code from some source and I don't know how to fix it since the logcat is showing a long fatal exception script highlighted in red. Thank you, I'll really appreciate it if someone can help.
From the error message in LogCat you can read that mSensor is null when you try to execute
mTextTitle.setText(mSensor.getStringType());
This means that the your sensor manager is unable to find a default sensor that matches the requested type
mSensor = mSensorManager.getDefaultSensor(mSensorType);
as stated in the documentation.

android app crashes on client start

I'm trying to make an app that connects to my tcp server on my pc to send text but every time I start the thread, my app crashes. please help. I just started using android studio so im not that familiar with it.
Here's my code:
package com.example.alex.hahanice;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class MainActivity extends AppCompatActivity {
Handler UIHandler;
Thread Thread1 = null;
public static final int SERVERPORT = 6000;
public static final String SERVERIP = "192.168.1.76";
#Override
protected void onCreate(Bundle savedInstanceState) {
this.Thread1 = new Thread(new Thread1());
this.Thread1.start();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View v) {
View view;
runOnUiThread(new Runnable() {
public void run() {
Thread1.start();
}
});
}
class Thread1 implements Runnable
{
public void run() {
Socket socket = null;
try
{
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
socket = new Socket(serverAddr, SERVERPORT);
Thread2 commThread = new Thread2(socket);
new Thread(commThread).start();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
class Thread2 implements Runnable
{
private Socket clientSocket;
private BufferedReader input;
public Thread2(Socket clientSocket)
{
this.clientSocket = clientSocket;
try
{
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
}
catch(IOException e)
{
e.printStackTrace();
}
}
public void run()
{
while(!Thread.currentThread().isInterrupted())
{
try
{
String read = input.readLine();
if(read != null)
{
//UIHandler.post(new updateUIThread(read));
}
else
{
Thread1 = new Thread(new Thread1());
Thread1.start();
return;
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}
Here's what the debugger says when I click on the button to start the thread to connect to my pc
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.alex.hahanice, PID: 3772
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:4659)
at android.view.View$PerformClick.run(View.java:19462)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5692)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4659) 
at android.view.View$PerformClick.run(View.java:19462) 
at android.os.Handler.handleCallback(Handler.java:733) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:146) 
at android.app.ActivityThread.main(ActivityThread.java:5692) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107) 
at dalvik.system.NativeStart.main(Native Method) 
Caused by: java.lang.IllegalThreadStateException: Thread already started
at java.lang.Thread.checkNotStarted(Thread.java:871)
at java.lang.Thread.start(Thread.java:1025)
at com.example.alex.hahanice.MainActivity$1.run(MainActivity.java:50)
at android.app.Activity.runOnUiThread(Activity.java:5001)
at com.example.alex.hahanice.MainActivity.onClick(MainActivity.java:48)
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
at android.view.View.performClick(View.java:4659) 
at android.view.View$PerformClick.run(View.java:19462) 
at android.os.Handler.handleCallback(Handler.java:733) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:146) 
at android.app.ActivityThread.main(ActivityThread.java:5692) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107) 
at dalvik.system.NativeStart.main(Native Method) 
Disconnected from the target VM, address: 'localhost:8600', transport: 'socket'
You are starting Thread at onCreate()
this.Thread1 = new Thread(new Thread1());
this.Thread1.start();
Then again starting the same thread at onClick()
Your problem is on this line:
Thread Thread1 = null;
You are setting the thread to a null value and that's where it says the error is coming from. Try assigning it a different value and see if that changes anything.

Android studio with TheMovieDB.com API wrapper : unable to start activity ComponentInfo and lots of other errors

I am using Android Studio 2.0(preview).
In order to display some info about certain movies , I downloaded Themoviedb.com API Wrapper by holgerbrandl
, added a dependency but just after I add two lines of the wrapper-related code I get a lot of errors I'm not familiar how to deal with.
TmdbMovies movies = new TmdbApi("myAPIkey_here").getMovies();
MovieDb movie = movies.getMovie(5353, "en");
I'm a very inexperienced newbie - thus the need of your help :)
If any details needed, please remind me to add them.
Here's my logcat :
11-29 02:35:26.710 5736-5736/com.example.michael.movienight W/System.err: SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
11-29 02:35:26.710 5736-5736/com.example.michael.movienight W/System.err: SLF4J: Defaulting to no-operation (NOP) logger implementation
11-29 02:35:26.710 5736-5736/com.example.michael.movienight W/System.err: SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
11-29 02:35:26.720 5736-5736/com.example.michael.movienight D/AndroidRuntime: Shutting down VM
11-29 02:35:26.720 5736-5736/com.example.michael.movienight E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.michael.movienight, PID: 5736
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.michael.movienight/com.example.michael.movienight.MainActivity}: info.movito.themoviedbapi.tools.MovieDbException: Failed to read configuration
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: info.movito.themoviedbapi.tools.MovieDbException: Failed to read configuration
at info.movito.themoviedbapi.TmdbApi.<init>(TmdbApi.java:48)
at info.movito.themoviedbapi.TmdbApi.<init>(TmdbApi.java:35)
at com.example.michael.movienight.MainActivity.onCreate(MainActivity.java:30)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
at java.net.InetAddress.lookupHostByName(InetAddress.java:431)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:188)
at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:157)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:100)
at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:357)
at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:340)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:433)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:384)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getHeaders(HttpURLConnectionImpl.java:150)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getHeaderFields(HttpURLConnectionImpl.java:210)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getHeaderFields(DelegatingHttpsURLConnection.java:178)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getHeaderFields(HttpsURLConnectionImpl.java)
at info.movito.themoviedbapi.tools.WebBrowser.readHeader(WebBrowser.java:226)
at info.movito.themoviedbapi.tools.WebBrowser.request(WebBrowser.java:143)
at info.movito.themoviedbapi.tools.WebBrowser.request(WebBrowser.java:112)
at info.movito.themoviedbapi.TmdbApi.requestWebPage(TmdbApi.java:64)
at info.movito.themoviedbapi.AbstractTmdbApi.mapJsonResult(AbstractTmdbApi.java:58)
at info.movito.themoviedbapi.AbstractTmdbApi.mapJsonResult(AbstractTmdbApi.java:45)
at info.movito.themoviedbapi.AbstractTmdbApi.mapJsonResult(AbstractTmdbApi.java:40)
at info.movito.themoviedbapi.TmdbConfig.getConfig(TmdbConfig.java:18)
at info.movito.themoviedbapi.TmdbApi.<init>(TmdbApi.java:44)
at info.movito.themoviedbapi.TmdbApi.<init>(TmdbApi.java:35) 
at com.example.michael.movienight.MainActivity.onCreate(MainActivity.java:30) 
at android.app.Activity.performCreate(Activity.java:6237) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
(full MainActivity.java below)
package com.example.michael.movienight;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import info.movito.themoviedbapi.TmdbApi;
import info.movito.themoviedbapi.TmdbMovies;
import info.movito.themoviedbapi.model.MovieDb;
public class MainActivity extends AppCompatActivity {
TextView MainText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
MainText = (TextView) findViewById(R.id.main_text);
TmdbMovies movies = new TmdbApi("my_API_key_here").getMovies();
MovieDb movie = movies.getMovie(5353, "en");
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I'm actually learning TheMovieDB API for a school project right now.
Apparently, whenever you want to use the network on android and connect to something, you need to put the statement inside an async task; something to do with network connections not working on the main thread.
To do this you can create a custom AsyncTask in your activity like so:
protected class MovieTask extends AsyncTask<Void, Void, MovieDB> {
protected MovieDB doInBackground(Void... v) {
TmdbMovies movies = new TmdbApi("myAPIkey_here").getMovies();
MovieDb movie = movies.getMovie(5353, "en");
return movie;
}
protected void onPostExecute(MovieDB movie) {
// Do something with movie
}
}
And your MainActivity onCreate would look like
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
MainText = (TextView) findViewById(R.id.main_text);
MovieTask mt = new MovieTask();
mt.execute();
}

Categories

Resources