Android Data Storage: Organizing Information in Key-Value Pairs

Greetings! I am currently developing an application and facing an issue that requires assistance.

log cat of the error:java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
                                                                               at cqdevelopers.incrediblediet.Fragment3.getAddressKeyValueFile(Fragment3.java:90)
                                                                               at cqdevelopers.incrediblediet.Fragment3.onCreateView(Fragment3.java:25)



<!-- begin snippet: js hide: false -->

<!-- language: lang-js -->

    05-16 02:25:21.711 6498-6498/cqdevelopers.incrediblediet E/AndroidRuntime: FATAL EXCEPTION: main
                                                                               Process: cqdevelopers.incrediblediet, PID: 6498
                                                                               java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
                                                                                   at cqdevelopers.incrediblediet.Fragment3.getAddressKeyValueFile(Fragment3.java:90)
                                                                                   at cqdevelopers.incrediblediet.Fragment3.onCreateView(Fragment3.java:25)
                                                                                   at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
                                                                                   at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
                                                                                   at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
                                                                                   at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:742)
                                                                                   at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
                                                                                   at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
                                                                                   at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
                                                                                   at android.support.v4.view.ViewPager.populate(ViewPager.java:1177)
                                                                                   at android.support.v4.view.ViewPager.populate(ViewPager.java:1025)
                                                                                   at android.support.v4.view.ViewPager$3.run(ViewPager.java:254)
                                                                                   at android.support.v4.view.ViewPager.completeScroll(ViewPager.java:1920)
                                                                                   at android.support.v4.view.ViewPager.onInterceptTouchEvent(ViewPager.java:2050)
                                                                                   at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2108)
                                                                                   at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553)
                                                                                   at android.view.Grou...

Fragment3.java:

public class Fragment3 extends Fragment {
    private EditText editText;
    private TextView textView;
    private Button button;

    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment3_layout, container, false);

        getAddressKeyValueFile();
        editText = (EditText) v.findViewById(R.id.tvadress);
        textView = (TextView) v.findViewById(R.id.textView);
        button = (Button) v.findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String address = null;

                address = editText.getText().toString();
                textView.setText(address);

                setAddressKeyValueFile(address);

            }
        });


        return v;
    }


    private void getAddressKeyValue() {
        SharedPreferences sharedPreferences = this.getActivity().getSharedPreferences("r", Context.MODE_PRIVATE);

        String key = getString(R.string.address);
        String existingAddress = sharedPreferences.getString(key, null);

        if (existingAddress != null) {

            TextView textView = (TextView) getActivity().findViewById(R.id.textView);
            textView.setText(existingAddress);

        }


    }

    private void setAddressKeyValue(String address)
    {
        SharedPreferences sharedPreferences = this.getActivity().getSharedPreferences("d" ,Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();

        String key = getString(R.string.address);
        editor.putString(key,address);

        editor.commit();


    }

    private void getAddressKeyValueFile()
    {
        Context context = getContext().getApplicationContext();

        String fileName = getString(R.string.filename);
        SharedPreferences sharedPreferences = context.getSharedPreferences(fileName,Context.MODE_PRIVATE);

        String key = getString(R.string.address);
        String existingAddress = sharedPreferences.getString(key,null);

        if(existingAddress != null)
        {
            TextView textView = (TextView) getActivity().findViewById(R.id.textView);
            textView.setText(existingAddress);
        }

    }


    private void setAddressKeyValueFile(String address)
    {
        Context context = getContext().getApplicationContext();
        String fileName = getString(R.string.filename);
        SharedPreferences sharedPreferences = context.getSharedPreferences(fileName,Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();

        String key = getString(R.string.address);
        editor.putString(key, address);

        editor.commit();
    }
}

And fragment3.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="cqdevelopers.incrediblediet.MainActivity$PlaceholderFragment">


    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/tvadress"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="register"
        android:id="@+id/textView2"
        android:layout_marginTop="23dp"
        android:layout_below="@+id/button"
        android:layout_centerHorizontal="true" />

    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/button"
        android:layout_below="@+id/tvadress"
        android:layout_centerHorizontal="true" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:id="@+id/textView"
        android:layout_marginTop="29dp"
        android:layout_below="@+id/textView2"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

If you could take a look at the exception and guide me where I might have made an error, your valuable assistance would be greatly appreciated. Thank you in advance.

Answer №1

rearrange the getAddressKeyValueFile method

//getAddressKeyValueFile();
editText = (EditText) v.findViewById(R.id.tvadress);
textView = (TextView) v.findViewById(R.id.textView);
getAddressKeyValueFile();

remove the following line:

TextView textView = (TextView) getActivity().findViewById(R.id.textView);

from inside the getAddressKeyValueFile() function

Answer №2

It appears that this particular code snippet

textView = (TextView) v.findViewById(R.id.textView);
is attempting to retrieve the TextView with the identifier textView from the layout of the activity rather than the fragment.

A suggested modification would be:

if(textView!=null){
    textView.setText(existingAddress);
}

This adjustment should be made in both the getAddressKeyValueFile() and getAddressKeyValue() methods.

Furthermore, within the onCreateView(...) method, ensure that getAddressKeyValueFile(); is only called once the textView object has been properly initialized.

Answer №3

Update the getAddressValueFile function to modify how the strings are retrieved.

private void getAddressKeyValueFile()
    {
        Context context = getContext().getApplicationContext();

        String fileName = getResources.getString(R.string.filename);
        SharedPreferences sharedPreferences = context.getSharedPreferences(fileName,Context.MODE_PRIVATE);

        String key = getResources.getString(R.string.address);
        String existingAddress = sharedPreferences.getString(key,null);

        if(existingAddress != null)
        {
            TextView textView = (TextView) getActivity().findViewById(R.id.textView);
            textView.setText(existingAddress);
        }

    }

Rather than using

getString(R.string.filename)

use

getResources.getString(R.string.filename)

Additionally, apply similar changes to the setAddressKeyValue method.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The ng-click event is unresponsive within the content of a bootstrap popover

I need to display a clickable table inside a popover, and trigger a function when a row is clicked. My HTML code appears as follows: <a popover id="showDays" type="button" class="btn btn-success btn-xs pull-left" data-toggle="popover" ...

What is the process of submitting a query request and then saving it as a variable in javascript?

As a beginner in SQL, JSON, and Fusion Table, I am looking to extract data from a Fusion Table and store it in a JavaScript variable, allowing me to display the data within a div element. This is the progress of my JavaScript code so far: var TopCity; To ...

Utilizing jQuery to divide an array into two separate arrays based on the unique ID

I am having trouble working with this array: The first id is 1 Items for the first id are: 12, 21, 34, and 33 The second id is 2 Items for the second id are: 21, 12, and 34 Here is how it looks in my array: arr = [12 1, 21 1, 34 1, 33 1, 21 2, 12 2, ...

Creating a customizable dropdown menu in HTML with potential Javascript integration

I'm looking to add a drop-down menu similar to an <options> tag within an HTML form. However, I also want users to have the ability to type in their own input if they choose, in addition to selecting from a predefined list of options. Essentiall ...

Display a loading GIF for every HTTP request made in Angular 4

I am a beginner with Angular and I am looking for a way to display a spinner every time an HTTP request is made. My application consists of multiple components: <component-one></component-one> <component-two></component-two> <c ...

Display or conceal a button in Angular 6 based on certain conditions

In my current project, I am facing a challenge where I need to disable a button while a task is running and then activate it once the task is complete. Specifically, I want a syncing icon to spin when the task status is 'In_progress' and then hid ...

Error Encountered in jQuery UI SelectMenu

Struggling to integrate the jQuery UI SelectMenu, I keep encountering the same error in the browser console. Below is the HTML Code: <select name="files" id="files"> <optgroup label="Scripts"> <option value="jquery">jQuery.js</ ...

Issue with jQuery animation: Background color does not change upon scrolling

Here is my fiddle link: https://jsfiddle.net/jzhang172/owkqmtcc/5/ I am attempting to change the background color of the "content" div when scrolling anywhere within it. The goal is for the background color to change when scrolling and revert back to its ...

Converting Jackson output to JSON in Angular

The server I'm currently working with made a change to the REST format, transitioning from plain JSON: { "removedVertices": [ { "id": "1", "info": { "host": "myhos ...

What is the best method to retrieve an Element using both its ID and value?

Is there a way to disable specific radio buttons based on both their id and value attributes? I have three radio buttons that need to be disabled. <input id="selectedAnswerIDforQ15" name="selectedAnswerIDforQ15" type="radio" value="78" /> <input ...

What should I do to resolve the error message TypeError: _components_firebase_Firebase__WEBPACK_IMPORTED_MODULE_2__.default.auth is not a valid function?

I have implemented Firebase with next.js and organized my files as shown below. However, I am encountering an issue with using the firebase client side SDK during the sign-up process. Firebase.js is where the firebase app is initialized import firebase fr ...

Why am I receiving the error message "Argument of type 'number' is not assignable to parameter of type 'never'?"

import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { showSecret = false; logArr ...

What is the best way to transfer variables in my specific scenario?

As I consider the optimal approach for managing my controllers, I find myself faced with a challenge of passing data between them. In my setup, I have multiple controllers that require sharing data throughout. For the first controller: app.controller(&a ...

How to adjust cell alignment in Handsontable

Handsontable showcases cell alignment options in the align cell demo: Horizontal Left Center Right Justify Vertical Top Middle Bottom Displayed below is a screenshot: To retrieve data, utilize the following code snippet: $('#table-wrapper&ap ...

I'm trying to figure out how to make HTML tags display within a React/Next <head> element

I inherited a React/Next project filled with spaghetti code. The previous developer did not prioritize SEO, and I am still learning React. Now, my main focus is getting tags to render in the Component. <Head> <meta key="data-tes ...

"Exploring the utilization of Access Control Lists within the Algolia Search platform

Looking for the best method to handle access control lists in Algolia. We have lists of items, but prefer not to use a universal list. Each user has unique listings. Our application utilizes an ACL logic - is it possible to integrate this access logic wi ...

The proportion in Highchart appears incorrect when utilizing a "logarithmic" y-axis type

I have encountered an issue with Highcharts in my AngularJS application. Specifically, I am using Highcharts JS v7.2.1 (2019-10-31). When I set the y-axis type to "logarithmic," it causes the bars to render incorrectly in terms of proportion. If I don&apos ...

How to retrieve variables passed from one Jade file to another Jade file

I've successfully set up a nodejs project that's linked to mongodb. In one of my jade files, I have a student list populated from the database, each with an edit button. Clicking on the edit button should take the user to another jade file called ...

How to bypass validation for required input in jQuery validate plugin

As an example, consider the <input name="surname" id="surname" type="text">. Sometimes I want to hide this input and make it non-required. My current workaround is to set a value such as "some value" when hiding the input, and then remove this value ...

Error: Trying to access the 'name' property of an undefined value in JSON

I encountered an issue displaying the error message below: TypeError: Cannot read properties of undefined (reading 'name') While developing a Discord bot using NodeJS and Discord.js, I have an empty JSON object where I append items whenever a ...