-2

My android app need to populate a ListView with a text from a web request, on a click from a button (on the toolbar). The question is, i'm working with sliding tabs with a toolbar and the list view stay on tab_1.xml . when i click on the button i have a null pointer exception on "populateList" . can anyone help?

MAIN ACTIVITY.JAVA

public class MainActivity extends ActionBarActivity {
private Toolbar mToolbar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"Home","Mês"};
int Numboftabs =2;
List<ValorWeb> valores = new ArrayList<ValorWeb>();
ListView valorListView;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    mToolbar = (Toolbar) findViewById(R.id.tool_bar);
    mToolbar.setTitle("Projeto Hidro Teste");
    setSupportActionBar(mToolbar);

    valorListView = (ListView) findViewById(R.id.listView);

    adapter = new ViewPagerAdapter(getSupportFragmentManager(), Titles, Numboftabs);

    pager = (ViewPager) findViewById(R.id.pager);
    pager.setAdapter(adapter);

    tabs = (SlidingTabLayout) findViewById(R.id.tabs);
    tabs.setDistributeEvenly(true);

    tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {

        @Override
        public int getIndicatorColor(int position) {
            return getResources().getColor(R.color.tabsScrollColor);
        }
    });

    tabs.setViewPager(pager);
}

private void populateList(){
    ArrayAdapter<ValorWeb> adapter = new ValorWebListAdapter();
    valorListView.setAdapter(adapter);
}

private void addvalor(String valor,String data){
    valores.add(new ValorWeb(valor, data));
}


private class ValorWebListAdapter extends ArrayAdapter<ValorWeb>{
    public ValorWebListAdapter(){

        super (MainActivity.this,R.layout.listview_item,valores);
    }


    @Override
    public View getView(int position,View view,ViewGroup parent) {
        if (view == null)
            view = getLayoutInflater().inflate(R.layout.listview_item, parent, false);

        ValorWeb currentValorWeb = valores.get(position);

        TextView valor = (TextView) view.findViewById(R.id.valortext);
        valor.setText(currentValorWeb.getValor());

        TextView data = (TextView) view.findViewById(R.id.datatext);
        data.setText(currentValorWeb.getData());
        return view;

    }

}


@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) {

    switch (item.getItemId()) {
        case R.id.action_refresh:

            String textFileUrl = "http://2015projetohidro.esy.es/arquivo.txt";
            String textFileText = "";

            Request httpRequest = new Request();
            httpRequest.execute(textFileUrl);
            try {
                textFileText = httpRequest.get(5000, TimeUnit.MILLISECONDS);
            } catch (InterruptedException | ExecutionException | TimeoutException e) {

                e.printStackTrace();
            }
            System.out.println("The online text file contains: " + textFileText);

            TextView textView = (TextView) findViewById(R.id.textConsumo);
            textView.setText(textFileText);

            String currentDateString = DateFormat.getDateInstance().format(new Date());

            TextView textdata = (TextView) findViewById(R.id.textData);
            textdata.setText(currentDateString);

            String currentTimeString = DateFormat.getTimeInstance().format(new Date());

            TextView textTime = (TextView) findViewById(R.id.texttime);
            textTime.setText(currentTimeString);

            addvalor(textView.getText().toString(),textdata.getText().toString());

            Toast.makeText(this,"Atualizando Consumo",Toast.LENGTH_LONG).show();

            populateList();

            return true;
        default:
            return super.onOptionsItemSelected(item);


    }
}}

ACTIVITYMAIN.XML

<LinearLayout 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:orientation="vertical"
tools:context=".MainActivity">

<include
    android:id="@+id/tool_bar"
    layout="@layout/tool_bar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

<tabs.SlidingTabLayout
    android:id="@+id/tabs"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/ColorPrimary"
    android:elevation="2dp" />

<android.support.v4.view.ViewPager
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1">
</android.support.v4.view.ViewPager>

TAB_1.XML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"

    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="0.0000"
    android:id="@+id/textConsumo"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="45dp"
    android:layout_marginRight="81dp"
    android:textSize="45dp"
    android:textColor="@color/ColorPrimary"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"

    android:textAppearance="?android:attr/textAppearanceSmall"
    android:text="m³"
    android:textSize="22dp"
    android:layout_gravity="center_horizontal"
    android:layout_marginLeft="15dp"
    android:layout_marginTop="-31dp"
    android:textColor="@color/ColorPrimary"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="data"
    android:textSize="17dp"
    android:id="@+id/textData"
    android:textColor="@color/ColorPrimary"
    android:layout_marginTop="8dp"
    android:layout_marginLeft="45dp" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:text="time"
    android:id="@+id/texttime"
    android:textColor="@color/ColorPrimary"
    android:textSize="17dp"
    android:layout_marginTop="-23dp"
    android:layout_marginLeft="175dp" />

<ListView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/listView"
    android:layout_marginTop="35dp" />

TAB_1.JAVA

public class Tab1 extends Fragment {


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



    return view;
}}

LOG

04-12 19:13:49.320  14496-14496/app.claudio.slidingtabs E/SELinux﹕ selinux_android_seapp_context_reload:  Error reading /seapp_contexts, line 16, name levelFrom, value container
04-12 19:13:59.600  14496-14496/app.claudio.slidingtabs E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.NullPointerException
            at app.claudio.slidingtabs.MainActivity.populateList(MainActivity.java:70)
            at app.claudio.slidingtabs.MainActivity.onOptionsItemSelected(MainActivity.java:150)
            at android.app.Activity.onMenuItemSelected(Activity.java:2640)
            at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:350)
            at android.support.v7.app.ActionBarActivity.onMenuItemSelected(ActionBarActivity.java:152)
            at android.support.v7.app.ActionBarActivityDelegate$1.onMenuItemSelected(ActionBarActivityDelegate.java:75)
            at android.support.v7.widget.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:44)
            at android.support.v7.internal.app.ToolbarActionBar$2.onMenuItemClick(ToolbarActionBar.java:76)
            at android.support.v7.widget.Toolbar$1.onMenuItemClick(Toolbar.java:164)
            at android.support.v7.widget.ActionMenuView$MenuBuilderCallback.onMenuItemSelected(ActionMenuView.java:738)
            at android.support.v7.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:802)
            at android.support.v7.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:153)
            at android.support.v7.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:949)
            at android.support.v7.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:939)
            at android.support.v7.widget.ActionMenuView.invokeItem(ActionMenuView.java:596)
            at android.support.v7.internal.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:145)
            at android.view.View.performClick(View.java:4476)
            at android.view.View$PerformClick.run(View.java:18795)
            at android.os.Handler.handleCallback(Handler.java:730)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:176)
            at android.app.ActivityThread.main(ActivityThread.java:5493)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1225)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1041)
            at dalvik.system.NativeStart.main(Native Method)
Mattia Maestrini
  • 32,270
  • 15
  • 87
  • 94
Claudio Castro
  • 191
  • 1
  • 1
  • 9
  • 1
    This is wrong man! you have list view in TAB1 xml and how can you find it in activity? find it inside fragment. This is why it is null pointer. – Harin Apr 13 '15 at 07:27

2 Answers2

1

You are setting your content view in onCreate method to : setContentView(R.layout.activity_main); and in onOptionsItemSelected(MenuItem item) - you are trying to get the textViews that are not in activity_main.xml but in TAB_1.XML. So, to solve this problem you should inflate the TAB_1.XML layout and than get the all textViews.

Change your code like below :

@Override
public boolean onOptionsItemSelected(MenuItem item) {

switch (item.getItemId()) {
    case R.id.action_refresh:

        String textFileUrl = "http://2015projetohidro.esy.es/arquivo.txt";
        String textFileText = "";

        Request httpRequest = new Request();
        httpRequest.execute(textFileUrl);
        try {
            textFileText = httpRequest.get(5000, TimeUnit.MILLISECONDS);
        } catch (InterruptedException | ExecutionException | TimeoutException e) {

            e.printStackTrace();
        }
        System.out.println("The online text file contains: " + textFileText);


        //Add this line 
        View view = getLayoutInflater().inflate(R.layout.tab_1, null);

        TextView textView = (TextView) view.findViewById(R.id.textConsumo);
        textView.setText(textFileText);
            String currentDateString =       DateFormat.getDateInstance().format(new Date());
        TextView textdata = (TextView) view.findViewById(R.id.textData);
        textdata.setText(currentDateString);

        String currentTimeString = DateFormat.getTimeInstance().format(new Date());

        TextView textTime = (TextView) view.findViewById(R.id.texttime);
        textTime.setText(currentTimeString);

        addvalor(textView.getText().toString(),textdata.getText().toString());

        Toast.makeText(this,"Atualizando Consumo",Toast.LENGTH_LONG).show();

        populateList();

        return true;
    default:
        return super.onOptionsItemSelected(item);


}

Hope this will help you!!!

The log file tells : EXCEPTION: main java.lang.NullPointerException at app.claudio.slidingtabs.MainActivity.populateList(MainActivity.java:70) at app.claudio.slidingtabs.MainActivity.onOptionsItemSelected(MainActivity.java:150)

I assume that line 70 in MainActivity.java is : valorListView.setAdapter(adapter); in which you are trying to set adapter to valorListView, but because your listView (valorListView) is not in main_activity.xml this causes the NullPointerException (as @Harry mentioned in the comment) .

Delete this line in onCreate: valorListView = (ListView) findViewById(R.id.listView);

and change the populateList like this :

  private void populateList(){
        ArrayAdapter<ValorWeb> adapter = new ValorWebListAdapter();

        View view = getLayoutInflater().inflate(R.layout.tab_1, null);

        valorListView = (ListView)view.findViewById(R.id.listView);
        valorListView.setAdapter(adapter);
    }

Edit : You should to the following steps :

put all code below in onCreate instead of in populateList:

 ArrayAdapter<ValorWeb> adapter = new ValorWebListAdapter();
 View view = getLayoutInflater().inflate(R.layout.tab_1, null);

valorListView = (ListView)view.findViewById(R.id.listView);
valorListView.setAdapter(adapter);

and change populateList like this:

 private void populateList(){
    addvalor(textView.getText().toString(),textdata.getText().toString());
    adapter.notifyDataSetChanged();

 }

Remove this line :

addvalor(textView.getText().toString(),textdata.getText().toString());

from OnOptonItemsSelected(), and set all your textViews global like this :

MAIN ACTIVITY.JAVA

public class MainActivity extends ActionBarActivity {
private Toolbar mToolbar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"Home","Mês"};
int Numboftabs =2;
List<ValorWeb> valores = new ArrayList<ValorWeb>();
ListView valorListView;
TextView textView,textTime,textdate; //Note this line


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
   //all your code goes here...

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
        case R.id.action_refresh:

            String textFileUrl = "http://2015projetohidro.esy.es/arquivo.txt";
            String textFileText = "";

            Request httpRequest = new Request();
            httpRequest.execute(textFileUrl);
            try {
                textFileText = httpRequest.get(5000, TimeUnit.MILLISECONDS);
            } catch (InterruptedException | ExecutionException | TimeoutException e) {

                e.printStackTrace();
            }
            System.out.println("The online text file contains: " + textFileText);

            textView = (TextView) findViewById(R.id.textConsumo);//Note this line
            textView.setText(textFileText);

            String currentDateString = DateFormat.getDateInstance().format(new Date());

            textdata = (TextView) findViewById(R.id.textData);//Note this line
            textdata.setText(currentDateString);

            String currentTimeString = DateFormat.getTimeInstance().format(new Date());

            textTime = (TextView) findViewById(R.id.texttime);//Note this line
            textTime.setText(currentTimeString);

            addvalor(textView.getText().toString(),textdata.getText().toString());

            Toast.makeText(this,"Atualizando Consumo",Toast.LENGTH_LONG).show();

            populateList();

            return true;
        default:
            return super.onOptionsItemSelected(item);


    }
}}
Josef
  • 442
  • 7
  • 16
0

I passed all the code for Tab1.java that inflate the tab_1.xml and it worked!

public class Tab1 extends Fragment {

List<ValorWeb> valores = new ArrayList<ValorWeb>();
ListView valorListView;

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.tab_1, container, false);
    setHasOptionsMenu(true);
    valorListView = (ListView) rootView.findViewById(R.id.listView);

    return rootView;
}


@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    // Inflate the menu; this adds items to the action bar if it is present.
    inflater.inflate(R.menu.menu_main, menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_refresh) {
        String textFileUrl = "http://2015projetohidro.esy.es/arquivo.txt";
        String textFileText = "";

        Request httpRequest = new Request();
        httpRequest.execute(textFileUrl);
        try {
            textFileText = httpRequest.get(5000, TimeUnit.MILLISECONDS);
        } catch (InterruptedException | ExecutionException | TimeoutException e) {

            e.printStackTrace();
        }
        System.out.println("The online text file contains: " + textFileText);


        TextView textView = (TextView) getView().findViewById(R.id.textConsumo);
        textView.setText(textFileText);

        String currentDateString = DateFormat.getDateInstance().format(new Date());

        TextView textdata = (TextView) getView().findViewById(R.id.textData);
        textdata.setText(currentDateString);

        String currentTimeString = DateFormat.getTimeInstance().format(new Date());

        TextView textTime = (TextView) getView().findViewById(R.id.texttime);
        textTime.setText(currentTimeString);

        addvalor(textView.getText().toString(), textTime.getText().toString());
        Toast.makeText(getActivity(), "Atualizando Consumo", Toast.LENGTH_SHORT).show();
        populateList();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

private void populateList() {
    ArrayAdapter<ValorWeb> adapter = new ValorWebListAdapter();
    valorListView.setAdapter(adapter);
}

private void addvalor(String valor, String data) {
    valores.add(new ValorWeb(valor, data));
}


private class ValorWebListAdapter extends ArrayAdapter<ValorWeb> {
    public ValorWebListAdapter() {

        super(Tab1.this.getActivity(), R.layout.listview_item, valores);
    }


    @Override
    public View getView(int position, View view, ViewGroup parent) {
        if (view == null)

            view = getActivity().getLayoutInflater().inflate(R.layout.listview_item, parent, false);

        ValorWeb currentValorWeb = valores.get(position);

        TextView valor = (TextView) view.findViewById(R.id.valortext);
        valor.setText(currentValorWeb.getValor());

        TextView data = (TextView) view.findViewById(R.id.datatext);
        data.setText(currentValorWeb.getData());
        return view;

    }

}}
Claudio Castro
  • 191
  • 1
  • 1
  • 9