My app has a SQlite database that I am trying to populate at initial install from a server. I am using volley to connect and have a web service on the server side. My issue is that on the first install when I call the method to populate the database it is obviously running on a different thread so before finishing it is moving on the building the UI. The UI is populated from the database so because the database has not been fulling populated I get error.
I have tried to force the volley call to run synchronously but just get a timeout exception
11-29 09:38:49.646 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: java.util.concurrent.TimeoutException
11-29 09:38:49.646 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: at com.android.volley.toolbox.RequestFuture.doGet(RequestFuture.java:121)
11-29 09:38:49.646 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: at com.android.volley.toolbox.RequestFuture.get(RequestFuture.java:97)
11-29 09:38:49.646 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: at com.clashtoolkit.clashtoolkit.network.ArmyNetworking.getTableFromServer(ArmyNetworking.java:93)
11-29 09:38:49.646 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: at com.clashtoolkit.clashtoolkit.database.DataCreator.getDatabaseFromServer(DataCreator.java:1657)
11-29 09:38:49.647 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: at com.clashtoolkit.clashtoolkit.UI.ArmyBuilder.onCreate(ArmyBuilder.java:46)
11-29 09:38:49.647 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: at android.app.Activity.performCreate(Activity.java:5990)
11-29 09:38:49.647 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
11-29 09:38:49.647 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
11-29 09:38:49.647 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
11-29 09:38:49.647 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: at android.app.ActivityThread.access$800(ActivityThread.java:151)
11-29 09:38:49.647 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
11-29 09:38:49.647 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
11-29 09:38:49.647 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: at android.os.Looper.loop(Looper.java:135)
11-29 09:38:49.648 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5257)
11-29 09:38:49.648 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: at java.lang.reflect.Method.invoke(Native Method)
11-29 09:38:49.648 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: at java.lang.reflect.Method.invoke(Method.java:372)
11-29 09:38:49.648 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
11-29 09:38:49.648 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
I cannot figure out the best way to do this. The DB has to be populated first, but I cannot seem to stop the UI code from running before it has been populated.
Main.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_army_builder);
//create and populate the database
DataCreator dbCreate = new DataCreator();
dbCreate.getDatabaseFromServer(this);
//creates the Toolbar and setting it as the Toolbar for the activity
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new TroopPagerAdapter(getSupportFragmentManager(), titles, numberOfTabs);
//Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.army_pager);
pager.setOffscreenPageLimit(4);
pager.setAdapter(adapter);
//assigning the sliding tab layout view
tabs = (SlidingTabLayout) findViewById(R.id.army_tabs);
//creating the icon portion of the sliding tabs
tabs.setCustomTabView(R.layout.custom_tabs, R.id.tabText);
//Setting custom color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.ColorPrimaryDark);
}
});
//Setting the ViewPager for the slidingtabsLayout
tabs.setViewPager(pager);
//Set the barracks fragments to the barracks viewpager
BuilderObjData builderObjData = new BuilderObjData();
ArrayList<Builder> barracksArray = builderObjData.getBuilderObjArray(this, Utilities.BUILDER_TYPE_BARRACKS);
bAdpter = new BarracksPagerAdapter(getSupportFragmentManager(), barracksArray);
bPager = (ViewPager) findViewById(R.id.barracks_pager);
bPager.setAdapter(bAdpter);
}
getDatabaseFromServer()
public void getDatabaseFromServer(Context context) {
Cursor cursor = context.getContentResolver().query(Container.CONTENT_URI, null, null, null, null);
if (cursor == null || cursor.getCount() == 0) {
for (String table : DataCreator.TABLES) {
ArmyNetworking.getTableFromServer(table, context);
}
if (cursor != null) {
cursor.close();
}
}
}
getTableFromServer()
public static void getTableFromServer(final String tableName, final Context context) {
Log.d(TAG, "called now");
String url = ArmyNetworking.WEB_BASE_URL + ArmyNetworking.PATH_TABLE + "/" + tableName;
// RequestFuture<JSONArray> future = RequestFuture.newFuture();
// JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, future, future);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET,
url,
(String) null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
updateTableFromServer(response, context, tableName);
Log.d(TAG, "got response");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//add error handling
}
});
VolleySingleton.getInstance(context).addToRequestQueue(jsonArrayRequest);
// try {
// JSONArray response = future.get(30, TimeUnit.SECONDS);
// updateTableFromServer(response, context, tableName);
//
// } catch (InterruptedException | ExecutionException | TimeoutException e) {
// e.printStackTrace();
// }
}
The above method shows the two different ways I tried to make the Volley call. The commented out code is to force it to be synchronous
Just add another activity at the start of your program, which shows a progress bar and a text like "Please wait while the data is loaded from the network, or check out our competitors' apps in the meantime".
Related
I appreciate your help with a problem with the ratingbar, I want to show the value of the ratingbar in a Toast when pressing a button, therefore each time you press the button, the value of the ratingbar should be displayed, however at the time pressing the button closes the application and debugging I get the following error.
"Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'float android.widget.RatingBar.getRating()' on a null object
reference at
com.org.notas.asembisencuesta.MainActivity.onClick(MainActivity.java:114)
"
#Override
protected void onCreate(Bundle savedInstanceState) {
commentsFra = new ComentariosFragment();
navhost = new HomeFragment();
thanks = new ThanksFragment();
}
public void onClick(View view){
ratingBar = findViewById(R.id.ratingBarOne);
transaction = getSupportFragmentManager().beginTransaction();
switch (view.getId()){
case R.id.fin_encuesta: {
transaction.replace(R.id.nav_host_fragment, thanks);
transaction.addToBackStack(null);
Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override public void run() {
transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.nav_host_fragment, navhost);
transaction.addToBackStack(null); transaction.commit();
}
};
handler.postDelayed(runnable,7000);
comments = findViewById(R.id.comments_dialog);
comments.setText(""); float rating; rating = ratingBar.getRating();
//Linea 114 Toast.makeText(this, ":" + rating, Toast.LENGTH_SHORT).show();
break;
}
transaction.commit();
}
}
This is the error that it generates:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.org.notas.asembisencuesta, PID: 7682
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(.java:414)
at android.view.View.performClick(View.java:7146)
at android.view.View.performClickInternal(View.java:7119)
at android.view.View.access$3500(View.java:803)
at android.view.View$(View.java:27533)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7386)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:980)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(.java:409)
at android.view.View.performClick(View.java:7146)
at android.view.View.performClickInternal(View.java:7119)
at android.view.View.access$3500(View.java:803)
at android.view.View$(View.java:27533)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7386)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:980)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'float android.widget.RatingBar.getRating()' on a null object reference
at com.org.notas.asembisencuesta.MainActivity.onClick(MainActivity.java:114)
at java.lang.reflect.Method.invoke(Native Method)
My app when installed on my relatively new Huawei running Oreo 8.0 is able to launch and run the app smoothly. The app also runs fine on the Nexus Emulator running Lollipop. However, on my other phone running KitKat 4.4 the app crashes when launched.
I think the problem occured when I added a default NavigationDrawerActivity.
09-05 14:05:57.285 30968-30968/? E/AndroidRuntime: FATAL EXCEPTION:
main
Process: com.example.a_phi.myapplication, PID: 30968
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.a_phi.myapplication/com.example.a_phi.myapplication.LoginActivity}:
android.view.InflateException: Binary XML file line #2: Error
inflating class
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2264)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2313)
at android.app.ActivityThread.access$1100(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1238)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5333)
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:895)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:711)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class
at android.view.LayoutInflater.createView(LayoutInflater.java:620)
at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:669)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:694)
at android.view.LayoutInflater.inflate(LayoutInflater.java:469)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:290)
at android.app.Activity.setContentView(Activity.java:1958)
at com.example.a_phi.myapplication.LoginActivity.onCreate(LoginActivity.java:44)
at android.app.Activity.performCreate(Activity.java:5340)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2228)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2313)
at android.app.ActivityThread.access$1100(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1238)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5333)
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:895)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:711)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at android.view.LayoutInflater.createView(LayoutInflater.java:594)
at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:669)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:694)
at android.view.LayoutInflater.inflate(LayoutInflater.java:469)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:290)
at android.app.Activity.setContentView(Activity.java:1958)
at com.example.a_phi.myapplication.LoginActivity.onCreate(LoginActivity.java:44)
at android.app.Activity.performCreate(Activity.java:5340)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2228)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2313)
at android.app.ActivityThread.access$1100(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1238)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5333)
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:895)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:711)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.huawei.android.content.res.ResourcesEx.getThemeDrawable(ResourcesEx.java:655)
at com.huawei.android.content.res.ResourcesEx.loadDrawable(ResourcesEx.java:623)
at android.content.res.TypedArray.getDrawable(TypedArray.java:616)
at android.view.View.(View.java:3573)
at android.view.ViewGroup.(ViewGroup.java:470)
at android.widget.LinearLayout.(LinearLayout.java:179)
at android.widget.LinearLayout.(LinearLayout.java:175)
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at android.view.LayoutInflater.createView(LayoutInflater.java:594)
at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:669)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:694)
at android.view.LayoutInflater.inflate(LayoutInflater.java:469)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:290)
at android.app.Activity.setContentView(Activity.java:1958)
at com.example.a_phi.myapplication.LoginActivity.onCreate(LoginActivity.java:44)
at android.app.Activity.performCreate(Activity.java:5340)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2228)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2313)
at android.app.ActivityThread.access$1100(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1238)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5333)
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:895)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:711)
at dalvik.system.NativeStart.main(Native Method)
LoginActvity
public class LoginActivity extends Activity {
private UserLoginTask mAuthTask = null;
// UI references.
private EditText mEmailView;
private EditText mPasswordView;
private TextView mRegistrationScreen;
private View mProgressView;
private View mLoginFormView;
public String id;
#Override
#TargetApi(19)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
setContentView(R.layout.activity_login_registration);
// Set up the login form.
mEmailView = (EditText) findViewById(R.id.email);
mPasswordView = (EditText) findViewById(R.id.password);
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
mRegistrationScreen = findViewById(R.id.registerLink);
mEmailSignInButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String emailAddress = mEmailView.getText().toString().trim();
String password = mPasswordView.getText().toString().trim();
UserLoginTask callDOIB = new UserLoginTask();
try {
String loginSuccessFail = callDOIB.execute(emailAddress, password).get();
try {
JSONObject jsonObject = new JSONObject(loginSuccessFail);
id = jsonObject.getString("id");
//JSONObject id = jArray.getJSONObject(0);
System.out.println("json object at LoginActivity id is "+id);
authoriseLogin(loginSuccessFail, id);
}catch (JSONException e){
e.printStackTrace();
}
}catch(InterruptedException e){
e.printStackTrace();
}
catch (ExecutionException e){
e.printStackTrace();
}
}
});
mRegistrationScreen.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Intent loadRegistration = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(loadRegistration);
}
});
}
public void authoriseLogin(String authorise, String id){
if (authorise.contains("id")) {
System.out.println(" accessLRA.authoriseLogin login has been called");
Session session = new Session(getApplicationContext());
session.setId(id);
Intent loadPersonal = new Intent(LoginActivity.this, MainActivity.class);
startActivity(loadPersonal);
System.out.println("Login has been authorised");
}
else{
System.out.println("Incorrect username or password");
}
}
}
It is giving me an inflate exception when loading the layout file using setContentView()
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.a_phi.myapplication/com.example.a_phi.myapplication.LoginActivity}:
android.view.InflateException: Binary XML file line #2: Error
inflating class
As suggested in the comments section, I was actually missing some other res -v21 folders which support API level 21 for Android KitKat. For some reason I didn't move them into my new project. It is working now, thank you.
I want to add a basic snackbar to my application but I have received an error that I couldn't figure out why.
I think the problem is getView(), may be that I must use getListView() but I am in a static context so how?
Here is my Java code:
public class SettingsFragment extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Display the fragment as the main content.
getFragmentManager().beginTransaction().replace(android.R.id.content,
new PrefsFragment()).commit();
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#4CAF50")));
}
public static class PrefsFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.settings);
Preference save_database = findPreference("savedatabase");
save_database.setOnPreferenceClickListener( new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick( Preference pref )
{
Data.bdd.Save_database(getActivity(),getView());
return true;
}
} );
final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager().findPreference("checkbox_always_on");
checkboxPref.
setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (newValue.toString().equals("true")) {
Screen.screen_on(getActivity());
Snackbar.make(getListView(),"Auto-extinction de l'écran désactivé",Snackbar.LENGTH_SHORT);
} else {
Screen.screen_off(getActivity());
Snackbar.make(getView(),"Auto-extinction de l'écran activé",Snackbar.LENGTH_SHORT);
}
return true;
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
view.setBackgroundColor(getResources().getColor(R.color.green_800));
return view;
}
}
Graddle dependencies :
compile 'com.android.support:appcompat-v7:23.0.0'
compile 'com.android.support:support-v13:23.0.0'
compile 'com.android.support:support-v4:23.0.0'
compile 'com.android.support:design:23.0.0'
compile 'com.android.support:recyclerview-v7:23.0.0'
I have this error that I do not understand
android.view.InflateException: Binary XML file line #18: Error inflating class android.support.design.widget.Snackbar$SnackbarLayout
at android.view.LayoutInflater.createView(LayoutInflater.java:640)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:750)
at android.view.LayoutInflater.inflate(LayoutInflater.java:483)
at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
at android.support.design.widget.Snackbar.<init>(Snackbar.java:183)
at android.support.design.widget.Snackbar.make(Snackbar.java:206)
at com.***.SettingsFragment$PrefsFragment$2.onPreferenceChange(SettingsFragment.java:87)
at android.preference.Preference.callChangeListener(Preference.java:1076)
at android.preference.TwoStatePreference.onClick(TwoStatePreference.java:64)
at android.preference.Preference.performClick(Preference.java:1131)
at android.preference.PreferenceScreen.onItemClick(PreferenceScreen.java:225)
at android.widget.AdapterView.performItemClick(AdapterView.java:334)
at android.widget.AbsListView.performItemClick(AbsListView.java:1531)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3667)
at android.widget.AbsListView$3.run(AbsListView.java:5590)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5944)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1389)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1184)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:288)
at android.view.LayoutInflater.createView(LayoutInflater.java:614)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:750)
at android.view.LayoutInflater.inflate(LayoutInflater.java:483)
at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
at android.support.design.widget.Snackbar.<init>(Snackbar.java:183)
at android.support.design.widget.Snackbar.make(Snackbar.java:206)
at com.***.SettingsFragment$PrefsFragment$2.onPreferenceChange(SettingsFragment.java:87)
at android.preference.Preference.callChangeListener(Preference.java:1076)
at android.preference.TwoStatePreference.onClick(TwoStatePreference.java:64)
at android.preference.Preference.performClick(Preference.java:1131)
at android.preference.PreferenceScreen.onItemClick(PreferenceScreen.java:225)
at android.widget.AdapterView.performItemClick(AdapterView.java:334)
at android.widget.AbsListView.performItemClick(AbsListView.java:1531)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3667)
at android.widget.AbsListView$3.run(AbsListView.java:5590)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5944)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1389)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1184)
Caused by: android.view.InflateException: Binary XML file line #34: Error inflating class <unknown>
at android.view.LayoutInflater.createView(LayoutInflater.java:640)
at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:55)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:689)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:748)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:813)
at android.view.LayoutInflater.inflate(LayoutInflater.java:480)
at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
at android.view.LayoutInflater.inflate(LayoutInflater.java:366)
at android.support.design.widget.Snackbar$SnackbarLayout.<init>(Snackbar.java:629)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:288)
at android.view.LayoutInflater.createView(LayoutInflater.java:614)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:750)
at android.view.LayoutInflater.inflate(LayoutInflater.java:483)
at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
at android.support.design.widget.Snackbar.<init>(Snackbar.java:183)
at android.support.design.widget.Snackbar.make(Snackbar.java:206)
at com.***.SettingsFragment$PrefsFragment$2.onPreferenceChange(SettingsFragment.java:87)
at android.preference.Preference.callChangeListener(Preference.java:1076)
at android.preference.TwoStatePreference.onClick(TwoStatePreference.java:64)
at android.preference.Preference.performClick(Preference.java:1131)
at android.preference.PreferenceScreen.onItemClick(PreferenceScreen.java:225)
at android.widget.AdapterView.performItemClick(AdapterView.java:334)
at android.widget.AbsListView.performItemClick(AbsListView.java:1531)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3667)
at android.widget.AbsListView$3.run(AbsListView.java:5590)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5944)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1389)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1184)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:288)
at android.view.LayoutInflater.createView(LayoutInflater.java:614)
at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:55)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:689)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:748)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:813)
at android.view.LayoutInflater.inflate(LayoutInflater.java:480)
at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
at android.view.LayoutInflater.inflate(LayoutInflater.java:366)
at android.support.design.widget.Snackbar$SnackbarLayout.<init>(Snackbar.java:629)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:288)
at android.view.LayoutInflater.createView(LayoutInflater.java:614)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:750)
at android.view.LayoutInflater.inflate(LayoutInflater.java:483)
at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
at android.support.design.widget.Snackbar.<init>(Snackbar.java:183)
at android.support.design.widget.Snackbar.make(Snackbar.java:206)
at com.***.SettingsFragment$PrefsFragment$2.onPreferenceChange(SettingsFragment.java:87)
at android.preference.Preference.callChangeListener(Preference.java:1076)
at android.preference.TwoStatePreference.onClick(TwoStatePreference.java:64)
at android.preference.Preference.performClick(Preference.java:1131)
at android.preference.PreferenceScreen.onItemClick(PreferenceScreen.java:225)
at android.widget.AdapterView.performItemClick(AdapterView.java:334)
at android.widget.AbsListView.performItemClick(AbsListView.java:1531)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3667)
at android.widget.AbsListView$3.run(AbsListView.java:5590)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5944)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1389)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1184)
Caused by: java.lang.RuntimeException: Failed to resolve attribute at index 5
at android.content.res.TypedArray.twGetColorStateList(TypedArray.java:438)
at android.widget.TextView.<init>(TextView.java:1388)
at android.widget.Button.<init>(Button.java:115)
at android.widget.Button.<init>(Button.java:108)
at android.widget.Button.<init>(Button.java:104)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:288)
at android.view.LayoutInflater.createView(LayoutInflater.java:614)
at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:55)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:689)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:748)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:813)
at android.view.LayoutInflater.inflate(LayoutInflater.java:480)
at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
at android.view.LayoutInflater.inflate(LayoutInflater.java:366)
at android.support.design.widget.Snackbar$SnackbarLayout.<init>(Snackbar.java:629)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:288)
at android.view.LayoutInflater.createView(LayoutInflater.java:614)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:750)
at android.view.LayoutInflater.inflate(LayoutInflater.java:483)
at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
at android.support.design.widget.Snackbar.<init>(Snackbar.java:183)
at android.support.design.widget.Snackbar.make(Snackbar.java:206)
at com.***.SettingsFragment$PrefsFragment$2.onPreferenceChange(SettingsFragment.java:87)
at android.preference.Preference.callChangeListener(Preference.java:1076)
at android.preference.TwoStatePreference.onClick(TwoStatePreference.java:64)
at android.preference.Preference.performClick(Preference.java:1131)
at android.preference.PreferenceScreen.onItemClick(PreferenceScreen.java:225)
at android.widget.AdapterView.performItemClick(AdapterView.java:334)
at android.widget.AbsListView.performItemClick(AbsListView.java:1531)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3667)
at android.widget.AbsListView$3.run(AbsListView.java:5590)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5944)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1389)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1184)
EDIT : my style
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
android:pre
<PreferenceCategory
android:title="General">
<CheckBoxPreference
android:key="checkbox_always_on"
android:title="Garder l'écran allumé"
android:defaultValue="false"/>
</PreferenceCategory>
<PreferenceCategory
android:title="Base de donnée">
<!--<ListPreference-->
<!--android:key="list_preference"-->
<!--android:title="General"-->
<!--android:dialogTitle="General"-->
<!--android:entries="#array/entries_list_preference"-->
<!--android:entryValues="#array/entryvalues_list_preference" />-->
<!--<Preference-->
<!--android:title="General">-->
<!--<intent android:action="android.intent.action.VIEW"-->
<!--android:data="http://codepath.com/" />-->
<!--</Preference>-->
<Preference
android:title="Sauvegarder la base de donnée sur la carte SD"
android:key="savedatabase">
</Preference>
</PreferenceCategory>
</PreferenceScreen>
So with the help of #YasinKaçmaz I found the answer to my problem. Here is my code
public class SettingsFragment extends AppCompatActivity {
static CoordinatorLayout coordinatorLayout;
Activity thisActivity=this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SnackbarShow.showSnackbar(thisActivity);
// Display the fragment as the main content.
getFragmentManager().beginTransaction().replace(android.R.id.content,
new PrefsFragment()).commit();
ActionBar bar = getSupportActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#4CAF50")));
}
public static class PrefsFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
Preference save_database = findPreference("savedatabase");
save_database.setOnPreferenceClickListener( new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick( Preference pref )
{
Data.bdd.Save_database(getActivity(),getView());
return true;
}
} );
final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager().findPreference("checkbox_always_on");
checkboxPref.
setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (newValue.toString().equals("true")) {
Screen.screen_on(getActivity());
showSnackbar(getView());
} else {
Screen.screen_off(getActivity());
showSnackbar(getView());
}
return true;
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
view.setBackgroundColor(getResources().getColor(R.color.green_800));
return view;
}
public static void showSnackbar(View view) {
Snackbar snackbar = Snackbar
.make(view, "There is one text", Snackbar.LENGTH_LONG)
.setAction("Action Text", new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.v("snackbar","yoo clicked action");
}
});
// Changing message text color
snackbar.setActionTextColor(Color.RED);
// Changing action button text color
View sbView = snackbar.getView();
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}
}
As per the documentation - https://developer.android.com/reference/android/support/design/widget/Snackbar.html#make(android.view.View,%20java.lang.CharSequence,%20int)
You will need parent view which will be pass to make() method as a first param,
So in your Fragment's layout file, find out the parent view, i.e. RelativeLayout or LinearLayout. Get the XML reference of the same using view.findViewById() method. And pass the object of the parent view as first parameter. Hope it will help!
I have this code in my Utils , can you try :
public static void showSnackbar(final Activity activity) {
Snackbar snackbar = Snackbar
.make(activity.findViewById(android.R.id.content), "There is one text", Snackbar.LENGTH_LONG)
.setAction("Action Text", new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.v("snackbar","yoo clicked action");
}
});
// Changing message text color
snackbar.setActionTextColor(Color.RED);
// Changing action button text color
View sbView = snackbar.getView();
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}
I currently am trying to pull down an RSS Feed as an XML file and I'm trying to use RXJava instead of an AsyncTask to parse and download the file.
I'm getting a network on the main thread error though while I'm trying to pull the feed down.
Here is the relevant code with observable which is in the main activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.rv_test_items);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
final ArrayList<TestItem> testItems = new ArrayList<>();
//testItems.add(new TestItem("Title here", "Content here"));
RssReader reader = new RssReader("http://www.feedforall.com/sample.xml");
// Subscribe on a new background thread, while returning the result on the UI thread.
// Using the RSS Classes we will pull the rss items from the rss feed and then create our
// own TestItem from them.
try {
Observable
.from(reader.getItems())
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<RssItem>() {
#Override
public void call(RssItem item) {
TestItem newItem = new TestItem(item.getTitle(), item.getDescription());
testItems.add(newItem);
}
});
} catch (Exception e) {
e.printStackTrace();
Log.e("App", "Failed to download RSS Items");
}
TestItemAdapter testItemAdapter = new TestItemAdapter(testItems);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(testItemAdapter);
And here is my RSSReader class
public class RssReader {
private String rssUrl;
public RssReader(String url) {
rssUrl = url;
}
public List<RssItem> getItems() throws Exception {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
//Creates a new RssHandler which will do all the parsing.
RssHandler handler = new RssHandler();
//Pass SaxParser the RssHandler that was created.
saxParser.parse(rssUrl, handler);
return handler.getRssItemList();
}
}
And my RSSHandler class
public class RssHandler extends DefaultHandler {
private List<RssItem> rssItemList;
private RssItem currentItem;
private boolean parsingTitle;
private boolean parsingLink;
private boolean parsingDescription;
public RssHandler() {
//Initializes a new ArrayList that will hold all the generated RSS items.
rssItemList = new ArrayList<RssItem>();
}
public List<RssItem> getRssItemList() {
return rssItemList;
}
//Called when an opening tag is reached, such as <item> or <title>
#Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equals("item"))
currentItem = new RssItem();
else if (qName.equals("title"))
parsingTitle = true;
else if (qName.equals("link"))
parsingLink = true;
else if (qName.equals("description"))
parsingDescription = true;
else if (qName.equals("media:thumbnail") || qName.equals("media:content") || qName.equals("image")) {
if (attributes.getValue("url") != null)
currentItem.setImageUrl(attributes.getValue("url"));
}
}
//Called when a closing tag is reached, such as </item> or </title>
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equals("item")) {
//End of an item so add the currentItem to the list of items.
rssItemList.add(currentItem);
currentItem = null;
} else if (qName.equals("title"))
parsingTitle = false;
else if (qName.equals("link"))
parsingLink = false;
else if (qName.equals("description"))
parsingDescription = false;
}
//Goes through character by character when parsing whats inside of a tag.
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (currentItem != null) {
//If parsingTitle is true, then that means we are inside a <title> tag so the text is the title of an item.
if (parsingTitle)
currentItem.setTitle(new String(ch, start, length));
//If parsingLink is true, then that means we are inside a <link> tag so the text is the link of an item.
else if (parsingLink)
currentItem.setLink(new String(ch, start, length));
//If parsingDescription is true, then that means we are inside a <description> tag so the text is the description of an item.
else if (parsingDescription)
currentItem.setDescription(new String(ch, start, length));
}
}
}
Stack trace
10-07 11:39:15.040 1959-1959/? I/art: Late-enabling -Xcheck:jni
10-07 11:39:15.208 1959-1959/? W/System.err: java.io.IOException: Couldn't open http://www.feedforall.com/sample.xml
10-07 11:39:15.208 1959-1959/? W/System.err: at org.apache.harmony.xml.ExpatParser.openUrl(ExpatParser.java:755)
10-07 11:39:15.208 1959-1959/? W/System.err: at org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:292)
10-07 11:39:15.208 1959-1959/? W/System.err: at javax.xml.parsers.SAXParser.parse(SAXParser.java:390)
10-07 11:39:15.208 1959-1959/? W/System.err: at javax.xml.parsers.SAXParser.parse(SAXParser.java:266)
10-07 11:39:15.208 1959-1959/? W/System.err: at com.polymorphicinc.retrofitsample.rss.RssReader.getItems(RssReader.java:36)
10-07 11:39:15.208 1959-1959/? W/System.err: at com.polymorphicinc.retrofitsample.ui.MainActivity.onCreate(MainActivity.java:47)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.app.Activity.performCreate(Activity.java:5990)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.app.ActivityThread.access$800(ActivityThread.java:151)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.os.Looper.loop(Looper.java:135)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5254)
10-07 11:39:15.208 1959-1959/? W/System.err: at java.lang.reflect.Method.invoke(Native Method)
10-07 11:39:15.209 1959-1959/? W/System.err: at java.lang.reflect.Method.invoke(Method.java:372)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
10-07 11:39:15.209 1959-1959/? W/System.err: Caused by: android.os.NetworkOnMainThreadException
10-07 11:39:15.209 1959-1959/? W/System.err: at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
10-07 11:39:15.209 1959-1959/? W/System.err: at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
10-07 11:39:15.209 1959-1959/? W/System.err: at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
10-07 11:39:15.209 1959-1959/? W/System.err: at java.net.InetAddress.getAllByName(InetAddress.java:215)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:272)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:382)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:332)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:199)
10-07 11:39:15.209 1959-1959/? W/System.err: at org.apache.harmony.xml.ExpatParser.openUrl(ExpatParser.java:753)
10-07 11:39:15.209 1959-1959/? W/System.err: ... 18 more
10-07 11:39:15.209 1959-1959/? E/App: Failed to download RSS Items
10-07 11:39:15.215 1959-1978/? D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
10-07 11:39:15.216 1959-1959/? D/: HostConnection::get() New Host Connection established 0xb42d9a00, tid 1959
10-07 11:39:15.219 1959-1959/? D/Atlas: Validating map...
10-07 11:39:15.281 1959-1978/? D/libEGL: loaded /system/lib/egl/libEGL_emulation.so
10-07 11:39:15.282 1959-1978/? D/libEGL: loaded /system/lib/egl/libGLESv1_CM_emulation.so
10-07 11:39:15.286 1959-1978/? D/libEGL: loaded /system/lib/egl/libGLESv2_emulation.so
10-07 11:39:15.295 1959-1978/? D/: HostConnection::get() New Host Connection established 0xb42d9b90, tid 1978
10-07 11:39:15.311 1959-1978/? I/OpenGLRenderer: Initialized EGL, version 1.4
10-07 11:39:15.360 1959-1978/? D/OpenGLRenderer: Enabling debug mode 0
10-07 11:39:15.381 1959-1978/? W/EGL_emulation: eglSurfaceAttrib not implemented
10-07 11:39:15.381 1959-1978/? W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xb424bb40, error=EGL_SUCCESS
Take a look at this to get an idea how to do it:
public class RssReader {
private String rssUrl;
public RssReader(String url) {
rssUrl = url;
}
public Observable<List<RssItem>> getItems() {
return Observable.create(new Observable.OnSubscribe<List<RssItem>>() {
#Override
public void call(Subscriber<? super List<RssItem>> subscriber) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
//Creates a new RssHandler which will do all the parsing.
RssHandler handler = new RssHandler();
//Pass SaxParser the RssHandler that was created.
saxParser.parse(rssUrl, handler);
subscriber.onNext(handler.getRssItemList());
subscriber.onCompleted();
} catch (Exception e) {
subscriber.onError(e);
}
}
});
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.rv_test_items);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
RssReader reader = new RssReader("http://www.feedforall.com/sample.xml");
reader.getItems()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<List<RssItem>>() {
#Override
public void call(List<RssItem> items) {
final ArrayList<TestItem> testItems = new ArrayList<>(items.size());
for (int size = items.size(), i = 0; i < size; i++) {
RssItem item = items.get(i);
testItems.add(new TestItem(item.getTitle(), item.getDescription()));
}
recyclerView.setAdapter(new TestItemAdapter(testItems));
}
}, new Action1<Throwable>() {
#Override
public void call(Throwable e) {
e.printStackTrace();
Log.e("App", "Failed to download RSS Items");
}
});
}
try this
Observable.defer(() -> Observable.from(reader.getItems())
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<RssItem>() {
#Override
public void call(RssItem item) {
TestItem newItem = new TestItem(item.getTitle(), item.getDescription());
testItems.add(newItem);
}
});
This question already exists:
Dropbox Core API is not working. I don't want to hardcode app key and secret?
Closed 7 years ago.
I am getting fatal exception error at main nullpointer exception. basically i have 2 activities login and main activity.you will enter app key and app secret in login activity then after authentication it will take you to main activity any help ??
login activity
public class login_activity extends AppCompatActivity {
public String APP_kEY ;
public String APP_SECRET;
public String accessToken;
EditText app_key_view;
EditText App_secret_view;
Button dropbox;
public DropboxAPI<AndroidAuthSession> mDBApi;
#Override
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences pref = getSharedPreferences("login",MODE_PRIVATE);
APP_kEY = pref.getString("appkey",null);
APP_SECRET = pref.getString("appsecret",null);
accessToken = pref.getString("access",null);
if (accessToken != null){
AppKeyPair appkeys = new AppKeyPair(APP_kEY,APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appkeys);
session.setOAuth2AccessToken(accessToken);
Intent i = new Intent(login_activity.this,MainActivity.class);
startActivity(i);
finish();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_activity);
app_key_view=(EditText)findViewById(R.id.app_key_text);
App_secret_view=(EditText)findViewById(R.id.app_secret_text);
dropbox = (Button)findViewById(R.id.link_dropbox);
//////////////////////////////////////////////////////////////
dropbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
APP_kEY = app_key_view.getText().toString();
APP_SECRET = App_secret_view.getText().toString();
AppKeyPair appKeys = new AppKeyPair(APP_kEY,APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeys);
mDBApi = new DropboxAPI<>(session);
mDBApi.getSession().startOAuth2Authentication(login_activity.this);
}
});
}
#Override
protected void onResume () {
super.onResume();
if(mDBApi.getSession().authenticationSuccessful()){
try {
mDBApi.getSession().finishAuthentication();
accessToken = mDBApi.getSession().getOAuth2AccessToken();
SharedPreferences.Editor editor = getSharedPreferences("login",MODE_PRIVATE).edit();
editor.putString("appkey",APP_kEY);
editor.putString("appsecret",APP_SECRET);
editor.putString("access",accessToken);
editor.commit();
Intent i = new Intent(login_activity.this,MainActivity.class);
startActivity(i);
finish();
}
catch (IllegalStateException e){
Log.i("DbAuthLog", "Error authenticationg", e);
}
}
}
Logcat
09-11 21:06:01.947 3842-3842/? I/art﹕ Late-enabling -Xcheck:jni
09-11 21:06:01.975 3842-3851/? I/art﹕ Debugger is no longer active
09-11 21:06:02.370 3842-3857/? I/art﹕ Background sticky concurrent mark sweep GC freed 2909(253KB) AllocSpace objects, 2(32KB) LOS objects, 0% free, 50MB/50MB, paused 36.891ms total 133.660ms
09-11 21:06:02.803 3842-3842/? D/AndroidRuntime﹕ Shutting down VM
09-11 21:06:02.803 3842-3842/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.ayzaz.timescopev1.timescope, PID: 3842
java.lang.RuntimeException: Unable to resume activity {com.example.ayzaz.timescopev1.timescope/com.example.ayzaz.timescopev1.timescope.login_activity}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.dropbox.client2.session.Session com.dropbox.client2.DropboxAPI.getSession()' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2986)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3017)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.dropbox.client2.session.Session com.dropbox.client2.DropboxAPI.getSession()' on a null object reference
at com.example.ayzaz.timescopev1.timescope.login_activity.onResume(login_activity.java:77)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1257)
at android.app.Activity.performResume(Activity.java:6076)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2975)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3017)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
09-11 21:06:05.849 3842-3842/com.example.ayzaz.timescopev1.timescope I/Process﹕ Sending signal. PID: 3842 SIG: 9
onResume() always gets called after onCreate().
When onResume() begins, mDBApi is null, because this field is only ever assigned in the onClick() method.
You either need to assign mDBApi in onCreate() directly, or you need to check that it is not null before you try to use it.