Must implement the interface while implemented this interface in a activity - java

I have a Main activity. at Main Activity, in Oncreat{}, i creat a fragment with name "ChannelList"
Code :
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//initVtcId();
setContentView(R.layout.activity_main);
FragmentManager fm = getSupportFragmentManager();
if (fm.findFragmentById(android.R.id.tabcontent) == null) {
FragmentTransaction fragmentTransaction = fm.beginTransaction();
ChannelList list = new ChannelList();
//fragmentTransaction.add(android.R.id.content, list);
fragmentTransaction.add(android.R.id.tabcontent, list);
fragmentTransaction.commit();
}
To oder to ChannelList to communicate up to a Activity with name "ChannelActivity". I use a Interface with name "OnListItemSelectedListener " and its method "onListItemSelected" in ChannelList
public class ChannelList extends ListFragment {
private OnListItemSelectedListener mCallback;
public interface OnListItemSelectedListener {
public void onListItemSelected(ListView l, int position);
}
The Fragment ChannelList captures the interface implementation during its onAttach() lifecycle method
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception.
try {
mCallback = (OnListItemSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnListItemSelectedListener");
}
}
the following method in the fragment is called when the user clicks on a list item. The fragment uses the callback interface to deliver the event to the parent activity.
public void onListItemClick(ListView l, View v, int position, long id) {
mCallback.onListItemSelected(l, mChannelAdapter.getItem(position)
.getID());
}
On ChannelActivity, I implement this interface and its method to call a Fragment with name "ChannelDetailFragment"
public class ChannelActivity extends FragmentActivity implements
ChannelList.OnListItemSelectedListener {
private FragmentManager fm;
private Fragment mChannelDetailFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.channel_activity);
fm = getSupportFragmentManager();
Fragment mChannelListFragment = fm
.findFragmentByTag(ChannelList.TAG);
if (mChannelListFragment == null) {
addFragment(new ChannelList(), false,
ChannelList.TAG);
}
}
#Override
public void onListItemSelected(ListView l, int position) {
Bundle args = new Bundle();
args.putInt(ChannelDetailFragment.CHANNEL_ID, position);
mChannelDetailFragment = fm
.findFragmentByTag(ChannelDetailFragment.TAG);
if (mChannelDetailFragment == null) {
mChannelDetailFragment = new ChannelDetailFragment();
}
mChannelDetailFragment.setArguments(args);
addFragment(mChannelDetailFragment, true, ChannelDetailFragment.TAG);
}
I follow this tut at:
http://developer.android.com/training/basics/fragments/communicating.html#Deliver
Unfortunately, I have an error throw from OnAttach{}. I checked my code manytimes but not detect where is incorrect. Sb help me!
10-02 14:07:40.156: E/AndroidRuntime(980): FATAL EXCEPTION: main
10-02 14:07:40.156: E/AndroidRuntime(980): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.channellistfragment/com.example.channellistfragment.MainActivity}: java.lang.ClassCastException: com.example.channellistfragment.MainActivity#a68d01b8 must implement OnListItemSelectedListener
10-02 14:07:40.156: E/AndroidRuntime(980): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
10-02 14:07:40.156: E/AndroidRuntime(980): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
10-02 14:07:40.156: E/AndroidRuntime(980): at android.app.ActivityThread.access$600(ActivityThread.java:130)
10-02 14:07:40.156: E/AndroidRuntime(980): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
10-02 14:07:40.156: E/AndroidRuntime(980): at android.os.Handler.dispatchMessage(Handler.java:99)
10-02 14:07:40.156: E/AndroidRuntime(980): at android.os.Looper.loop(Looper.java:137)
10-02 14:07:40.156: E/AndroidRuntime(980): at android.app.ActivityThread.main(ActivityThread.java:4745)
10-02 14:07:40.156: E/AndroidRuntime(980): at java.lang.reflect.Method.invokeNative(Native Method)
10-02 14:07:40.156: E/AndroidRuntime(980): at java.lang.reflect.Method.invoke(Method.java:511)
10-02 14:07:40.156: E/AndroidRuntime(980): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
10-02 14:07:40.156: E/AndroidRuntime(980): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-02 14:07:40.156: E/AndroidRuntime(980): at dalvik.system.NativeStart.main(Native Method)
10-02 14:07:40.156: E/AndroidRuntime(980): Caused by: java.lang.ClassCastException: com.example.channellistfragment.MainActivity#a68d01b8 must implement OnListItemSelectedListener
10-02 14:07:40.156: E/AndroidRuntime(980): at com.example.channellistfragment.ChannelList.onAttach(ChannelList.java:79)
10-02 14:07:40.156: E/AndroidRuntime(980): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:867)
10-02 14:07:40.156: E/AndroidRuntime(980): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
10-02 14:07:40.156: E/AndroidRuntime(980): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
10-02 14:07:40.156: E/AndroidRuntime(980): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
10-02 14:07:40.156: E/AndroidRuntime(980): at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:551)
10-02 14:07:40.156: E/AndroidRuntime(980): at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1163)
10-02 14:07:40.156: E/AndroidRuntime(980): at android.app.Activity.performStart(Activity.java:5018)
10-02 14:07:40.156: E/AndroidRuntime(980): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2032)
10-02 14:07:40.156: E/AndroidRuntime(980): ... 11 more

You have 2 activities and add ChannelList fragment to both of them. First one (Main Activity) doesnt implements your callback interface and you get ClassCast exeption.

Related

Error using arrayList passed in Intent

I am passing an arrayList to another activity using this in my main activity:
Intent i = new Intent(getApplicationContext(),PairedDevices.class);
i.putExtra("arrayListPaired", arrayListpaired);
startActivity(i);
To be passed to an actvity called PairedDevices where I want to display that array list. Here is the PairedDevices class:
public class PairedDevices extends Activity {
ListView listViewPaired;
ArrayList<String> pairedDevices = (ArrayList<String>) getIntent().getSerializableExtra("arrayListPaired");
ArrayAdapter<String> listAdapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_paired_devices);
listViewPaired = (ListView)findViewById(R.id.listViewPaired);
listAdapter = new ArrayAdapter<String>(PairedDevices.this, android.R.layout.simple_list_item_1, pairedDevices);
listViewPaired.setAdapter(listAdapter);
}
}
It is crashing and I am getting the following stacktrace, Any advice on how to fix this would be greatly appreciated!:
10-28 02:04:10.101 25536-25536/my.obd2connector E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: my.obd2connector, PID: 25536
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{my.obd2connector/my.obd2connector.PairedDevices}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2231)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
at android.app.ActivityThread.access$900(ActivityThread.java:161)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5356)
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:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at my.obd2connector.PairedDevices.<init>(PairedDevices.java:17)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2222)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
            at android.app.ActivityThread.access$900(ActivityThread.java:161)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:157)
            at android.app.ActivityThread.main(ActivityThread.java:5356)
            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:1265)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
            at dalvik.system.NativeStart.main(Native Method)
Put this in onCreate
pairedDevices = (ArrayList<String>) getIntent().getSerializableExtra("arrayListPaired");
like this
public class PairedDevices extends Activity
{
ListView listViewPaired;
ArrayList<String> pairedDevices = null;
ArrayAdapter<String> listAdapter;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_paired_devices);
listViewPaired = (ListView)findViewById(R.id.listViewPaired);
pairedDevices = (ArrayList<String>)getIntent().getSerializableExtra("arrayListPaired");
listAdapter = new ArrayAdapter<String>(PairedDevices.this, android.R.layout.simple_list_item_1, pairedDevices);
listViewPaired.setAdapter(listAdapter);
}
}
place this code in onCreate();
ArrayList<String> pairedDevices = (ArrayList<String>) getIntent().getSerializableExtra("arrayListPaired");
Replace this code to solve your error
Intent i = new Intent(getApplicationContext(),PairedDevices.class);
i.putStringArrayListExtra("arrayListPaired", arrayListpaired);
startActivity(i);
And This code replace in PairedDevices file
ArrayList<String> pairedDevices = (ArrayList<String>) getIntent().getStringArrayListExtra("arrayListPaired");

Android NumberPicker NullPointer why?

i am try to implement a numberPicker to select minute values.
But i am getting a NullPointer Exception at this line:
minutePicker = (NumberPicker) findViewById(R.id.minuten_picker);
Following Code:
public class MainActivity extends Activity {
NumberPicker minutePicker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Auswahl Minuten zum starten / Stoppen aller
minutePicker = new NumberPicker(MainActivity.this);
minutePicker = (NumberPicker) findViewById(R.id.minuten_picker);
minutePicker.setMaxValue(30);
minutePicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
abschaltzeit = minutePicker.getValue();
}
});
minutePicker.setValue(0);
minutePicker.setWrapSelectorWheel(false);
}
}
XML:
<NumberPicker
android:id="#+id/minuten_picker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_row="6"
android:layout_column="0"
android:paddingLeft="20dp" />
Log:
09-25 11:00:09.749 10687-10687/de.carsten.awesome.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: de.carsten.awesome.app, PID: 10687
java.lang.RuntimeException: Unable to start activity ComponentInfo{de.carsten.awesome.app/de.carsten.awesome.app.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at de.carsten.awesome.app.MainActivity.onCreate(MainActivity.java:83)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
minutePicker = new NumberPicker(MainActivity.this);
minutePicker = (NumberPicker) findViewById(R.id.minuten_picker);
You're creating a NumberPicker programmatically and then overwriting the reference with whatever findViewById() returns. It returns null if your activity_main layout does not contain a minuten_picker.
Choose only the other: either create it prorgrammatically or find it from a view hierarchy you inflated.
If you choose the programmatic way new NumberPicker(), remember to add it to some layout in your activity view hierarchy, e.g. with setContentView()
If you choose the inflation way, make sure you have the view in your XML layout file.
I'm guessing the NPE you're seeing is actually on the following line where you're trying to invoke a method on the minutePicker and it's null.
I apologize.
I moved the Code from the MainActivity in the creating Fragment and it works with rootView.findView.
Sorry but i am new with the Fragement Konzept.
Thanks a lot for your help !

how to set listadapter for fragment

I have two framelayout in my main.xml file. I add framelayouts to the class that extends Fragment. my main class extends FragmentActivity and this is Oncreate method of it:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FragmentManager fm =getFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
Fragment f=new Freg1();
Fragment f2=new Freg1();
ft.add(R.id.frame1, f);
ft.add(R.id.frame2, f2);
ft.commit();
tf=Typeface.createFromAsset(this.getAssets(),"font/Byekan.ttf" );
tv1=(TextView) findViewById(R.id.textView1);
tv1.setTypeface(tf);
Log.i(TAG,"1");
lv1=(ListView) findViewById(R.id.listView1);
lv2=(ListView) findViewById(R.id.listView2);
Log.i(TAG,"2");
List<String> stringList = new ArrayList<String>(Arrays.asList(s1));
Log.i(TAG,"3");
ListAdapter listAdapter = new CustomListAdapter(MainActivity.this , R.layout.custom_list ,stringList);
Log.i(TAG,"4");
lv1.setAdapter(listAdapter);
Log.i(TAG,"5");
lv2.setAdapter(listAdapter);
Log.i(TAG,"6");
}
when i run the codes, it crashed after LOG no4. that mean setAdapter() method do not work. how can i resolve this problem?
this is my logcat resource:
Shutting down VM
threadid=1: thread exiting with uncaught exception (group=0x40a13300)
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.taxitabriz/com.example.taxitabriz.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.taxitabriz.MainActivity.onCreate(MainActivity.java:55)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
... 11 more
thank for you that help me to resolve problem.
Your ListView lv1 is null as you can see here:
java.lang.RuntimeException: Unable to start activity ComponentInfo{...}: java.lang.NullPointerException
....
com.example.taxitabriz.MainActivity.onCreate(MainActivity.java:55)
The line 55 of MainActivity should be this call: lv1.setAdapter(listAdapter);
Make sure that your listView1 is included within the layout and initialized correctly prior to trying to set an Adapter to it.

AsyncTask #1 :An error occured while executing doInBackground()

I am developing app with Jsoup. The problem is it is not working when I am calling it from other class with the help of Getters. But it is running when I call it within Single Activity. I am not able to find why exactly it is not working, as it should.
Here are the logCat files with all the activities.
LogCat
11-14 20:16:52.063: E/AndroidRuntime(1871): FATAL EXCEPTION: AsyncTask #1
11-14 20:16:52.063: E/AndroidRuntime(1871): java.lang.RuntimeException: An error occured while executing doInBackground()
11-14 20:16:52.063: E/AndroidRuntime(1871): at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-14 20:16:52.063: E/AndroidRuntime(1871): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
11-14 20:16:52.063: E/AndroidRuntime(1871): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
11-14 20:16:52.063: E/AndroidRuntime(1871): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
11-14 20:16:52.063: E/AndroidRuntime(1871): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-14 20:16:52.063: E/AndroidRuntime(1871): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
11-14 20:16:52.063: E/AndroidRuntime(1871): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
11-14 20:16:52.063: E/AndroidRuntime(1871): at java.lang.Thread.run(Thread.java:856)
11-14 20:16:52.063: E/AndroidRuntime(1871): Caused by: java.lang.IllegalArgumentException: Must supply a valid URL
11-14 20:16:52.063: E/AndroidRuntime(1871): at org.jsoup.helper.Validate.notEmpty(Validate.java:102)
11-14 20:16:52.063: E/AndroidRuntime(1871): at org.jsoup.helper.HttpConnection.url(HttpConnection.java:57)
11-14 20:16:52.063: E/AndroidRuntime(1871): at org.jsoup.helper.HttpConnection.connect(HttpConnection.java:27)
11-14 20:16:52.063: E/AndroidRuntime(1871): at org.jsoup.Jsoup.connect(Jsoup.java:73)
11-14 20:16:52.063: E/AndroidRuntime(1871): at com.example.frgbdf.jsoupAct$Parsee.doInBackground(jsoupAct.java:30)
11-14 20:16:52.063: E/AndroidRuntime(1871): at com.example.frgbdf.jsoupAct$Parsee.doInBackground(jsoupAct.java:1)
11-14 20:16:52.063: E/AndroidRuntime(1871): at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-14 20:16:52.063: E/AndroidRuntime(1871): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
11-14 20:16:52.063: E/AndroidRuntime(1871): ... 4 more
MainActivity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent i = new Intent(getApplicationContext(), LineGraph.class);
startActivity(i);
}
}
LineGraph
public class LineGraph extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
jsoupAct mJsoupAct = new jsoupAct();
String parseStrings;
parseStrings = mJsoupAct.getOutput();
Log.d("xstring", parseStrings + "");
}
}
jsoupAct
public class jsoupAct extends Activity {
String output = "00";
String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
url = "www.google.com";
}
public void mExecute() {
new Parsee().execute();
}
public class Parsee extends AsyncTask<String, String, String> {
protected String doInBackground(String... params) {
try {
Document doc = Jsoup.connect(url).get();
String body = doc.body().text();
output = body.toString();
} catch (IOException e) {
e.printStackTrace();
}
return output;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(output);
}
}
public String getOutput() {
mExecute();
return output;
}
public void setOutput(String output) {
this.output = output;
}
}
You are specifying the URL in a string local to the jsoupAct activity. The string will be null if you try to access from other Activities. To solve it move the string inside the AsyncTask class and it will work
Or add empty constructor to the jsonAct activity and assign the value of url in it. onCreate() is called only when to start an activity using the startActivity()
You have already answered your own question:
Caused by: java.lang.IllegalArgumentException: Must supply a valid URL
at org.jsoup.helper.Validate.notEmpty(Validate.java:102)
at org.jsoup.helper.HttpConnection.url(HttpConnection.java:57)
at org.jsoup.helper.HttpConnection.connect(HttpConnection.java:27)
at org.jsoup.Jsoup.connect(Jsoup.java:73)
at com.example.frgbdf.jsoupAct$Parsee.doInBackground(jsoupAct.java:30)
at com.example.frgbdf.jsoupAct$Parsee.doInBackground(jsoupAct.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
... 4 more

Creating a ListView with custom list items programmatically in Android - no xml list item layout

As I have seen on previously asked questions, inside the custom adapter class (say, MyAdapter extends ArrayAdapter) they always use an inflated xml list-item layout. What I am hoping to do is create everything entirely using Java and no XML...
// for example
String[] wordlist = new String[] {a, b, c};
LinearLayout list_item_layout = new LinearLayout(this);
list_item_layout.setId(5000);
TextView listText = new TextView(this);
listText.setId(5001);
listLayout.addView(listText);
ListView list = new ListView(this);
// ** QUESTION ** do I declare a programmatic .setAdapter() like this?
// ** TAKE NOTE ** I passed 'wordlist' here..
list.setAdapter(new MyAdapter(this, list_item_layout.getId(), listText.getId(), wordlist));
and then for MyAdapter...
private class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context context, int resource, int textViewResourceId, String[] strings) {
super(context, resource, textViewResourceId, strings);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView; //is this the list_item_layout that I passed??
TextView tv = (TextView) v.findViewById(5001);
// ** QUESTION ** do I pass 'wordlist' again here?
tv.setText( wordlist[position] );
return v;
}
}
What happens when I run this on my device is I get the following errors...
10-08 23:11:19.775: E/AndroidRuntime(18276): FATAL EXCEPTION: main
10-08 23:11:19.775: E/AndroidRuntime(18276): android.content.res.Resources$NotFoundException: String resource ID #0x0
10-08 23:11:19.775: E/AndroidRuntime(18276): at android.content.res.Resources.getText(Resources.java:222)
10-08 23:11:19.775: E/AndroidRuntime(18276): at android.widget.TextView.setText(TextView.java:3011)
10-08 23:11:19.775: E/AndroidRuntime(18276): at com.turista.client.TuristaClientMain.onClick(TuristaClientMain.java:113)
10-08 23:11:19.775: E/AndroidRuntime(18276): at android.view.View.performClick(View.java:2538)
10-08 23:11:19.775: E/AndroidRuntime(18276): at android.view.View$PerformClick.run(View.java:9152)
10-08 23:11:19.775: E/AndroidRuntime(18276): at android.os.Handler.handleCallback(Handler.java:587)
10-08 23:11:19.775: E/AndroidRuntime(18276): at android.os.Handler.dispatchMessage(Handler.java:92)
10-08 23:11:19.775: E/AndroidRuntime(18276): at android.os.Looper.loop(Looper.java:123)
10-08 23:11:19.775: E/AndroidRuntime(18276): at android.app.ActivityThread.main(ActivityThread.java:3691)
10-08 23:11:19.775: E/AndroidRuntime(18276): at java.lang.reflect.Method.invokeNative(Native Method)
10-08 23:11:19.775: E/AndroidRuntime(18276): at java.lang.reflect.Method.invoke(Method.java:507)
10-08 23:11:19.775: E/AndroidRuntime(18276): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:847)
10-08 23:11:19.775: E/AndroidRuntime(18276): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
10-08 23:11:19.775: E/AndroidRuntime(18276): at dalvik.system.NativeStart.main(Native Method)
Can anyone explain how to do this programmatically?
* EDITED * October 9, 2012
Ok, as I am still stuck in this issue I think I've made some improvements but still get error messages. The improved code is as follows..
//wordlist is a global variable
String[] wordlist = new String[] {a, b, c};
// ..
// .. inside onCreate...
ListView list = new ListView(this);
list.setAdapter(new MyAdapter(this, R.layout.listitem, R.id.mLargeTextView, wordlist));
// since the ArrayAdapter class needs XML parameters to inflate, I created a dummy layout
now inside MyAdapter class..
private class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context context, int resource, int textViewResourceId, String[] strings) {
super(context, resource, textViewResourceId, strings);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout listLayout = new LinearLayout(Main.this);
listLayout.setLayoutParams(new LayoutParams(wrapContent, wrapContent));
listLayout.setId(5000);
TextView listText = new TextView(Main.this);
listText.setId(5001);
listLayout.addView(listText);
listText.setText(wordlist[position]);
return listLayout;
}
}
As you can see, I think I have to override getView in order to display my custom view so this is what I did. Unfortunately I think I misunderstood it. Here are the errors..
10-09 09:24:10.095: E/AndroidRuntime(2517): FATAL EXCEPTION: main
10-09 09:24:10.095: E/AndroidRuntime(2517): java.lang.ClassCastException: android.view.ViewGroup$LayoutParams
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.widget.ListView.measureScrapChild(ListView.java:1183)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.widget.ListView.measureHeightOfChildren(ListView.java:1266)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.widget.ListView.onMeasure(ListView.java:1175)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.view.View.measure(View.java:8366)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.view.View.measure(View.java:8366)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.view.View.measure(View.java:8366)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1017)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.widget.LinearLayout.measureVertical(LinearLayout.java:386)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.widget.LinearLayout.onMeasure(LinearLayout.java:309)
10-09 09:24:10.095: E/AndroidRuntime(2517): at com.android.internal.widget.WeightedLinearLayout.onMeasure(WeightedLinearLayout.java:60)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.view.View.measure(View.java:8366)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.view.View.measure(View.java:8366)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.view.View.measure(View.java:8366)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.view.ViewRoot.performTraversals(ViewRoot.java:847)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.view.ViewRoot.handleMessage(ViewRoot.java:1868)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.os.Handler.dispatchMessage(Handler.java:99)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.os.Looper.loop(Looper.java:123)
10-09 09:24:10.095: E/AndroidRuntime(2517): at android.app.ActivityThread.main(ActivityThread.java:3691)
10-09 09:24:10.095: E/AndroidRuntime(2517): at java.lang.reflect.Method.invokeNative(Native Method)
10-09 09:24:10.095: E/AndroidRuntime(2517): at java.lang.reflect.Method.invoke(Method.java:507)
10-09 09:24:10.095: E/AndroidRuntime(2517): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:847)
10-09 09:24:10.095: E/AndroidRuntime(2517): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
10-09 09:24:10.095: E/AndroidRuntime(2517): at dalvik.system.NativeStart.main(Native Method)
ListView extends AbsListView which in turn extends AdapterView which extends view group. So all the child of ListView would be added to ViewGroup. So to set the layout param, you can
use ViewGroup.LayoutParam while setting layout param for listLayout.
Or try AbsListView.LayoutParams for setting layout param for listLayout
Please try it and let me know if it worked.
Following code is working fine..
public class MainActivity1 extends Activity {
String[] wordlist = new String[] { "a", "b", "c" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView list = new ListView(this);
list.setAdapter(new MyAdapter(this, wordlist));
setContentView(list);
}
private class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context context, String[] strings) {
super(context, -1, -1, strings);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout listLayout = new LinearLayout(MainActivity1.this);
listLayout.setLayoutParams(new AbsListView.LayoutParams(
AbsListView.LayoutParams.WRAP_CONTENT,
AbsListView.LayoutParams.WRAP_CONTENT));
listLayout.setId(5000);
TextView listText = new TextView(MainActivity1.this);
listText.setId(5001);
listLayout.addView(listText);
listText.setText(super.getItem(position));
return listLayout;
}
}
}
The problem was that by default Eclipse imports ViewGroup.LayoutParams which are incompatible with the AbsListView.LayoutParams which need to be used for setting layout param for view returned from the getView() method.
Please check and let me know how it went..
To add to the above answer, setting id with a constant number is not a good idea.
Replace, listLayout.setId(5000); with,listLayout.setId(View.generateViewId());
In case you are targeting API 16 and below, refer this.

Categories