Error in creating horizontal scroll view?
I am working in android, i want to make a scrollview. this is my code for that :
package com.pericent;
import android.app.Activity;
import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.ViewGroup.LayoutParams;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TextView;
public class HelloTabWidget extends Activity {
private String TAG="HelloTabWidget";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanc开发者_开发知识库eState);
Log.v(TAG,"i am just before everything");
HorizontalScrollView hr=new HorizontalScrollView(this);
hr.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
LinearLayout layout=new LinearLayout(this);
LinearLayout mainlayout=new LinearLayout(this);
mainlayout=(LinearLayout)findViewById(R.id.upper1);
layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
Log.v(TAG,"i am just after the declarations");
for(int i=0;i<100;i++){
TextView txt=new TextView(this);
txt.setText("Text " + i );
layout.addView(txt);
}
Log.v(TAG,"i am after the for loop");
hr.addView(layout);
mainlayout.addView(hr);//<<---this is creating NullPointerException
setContentView(R.layout.cecking);
Log.v(TAG,"i am after the everything");
}
}
and this my cecking.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/upper1">
</LinearLayout>
whenever i run the program, this error is occurred:-
Unable to start activity ComponentInfo{com.pericent/com.pericent.HelloTabWidget}: java.lang.NullPointerException
and in this line the error is occurred:- mainlayout.addView(hr);
please help me to find out the reason of error. Thank you in advance.
You are not setting any layout for the Activity
as well as you are not Inflating checking.xml for that Activity.
That's why mainlayout cannot be found and cause NullPointerException
Try this way:
checking.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/upper1">
</LinearLayout>
</LinearLayout>
and then set your layout inside onCreate()
of the Activity
like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContenView(R.layout.checking);
mainlayout=(LinearLayout)findViewById(R.id.upper1);
}
This might be because you haven't set
.setLayoutParams(new Layout...
for mainlayout, the error statement line object.
精彩评论