i'm having an issue with android development (i'm a newbiew btw) ..
i'm trying to accomplish this tutorial : http://developer.android.com/training/basics/firstapp/starting-activity.html, except that my problem is that the second activity crashes systematically and i dont know why ..
when i comment the line : setContentView(textView1): the second activity doesnt crash, but the text is not shown . so i guess thats where my problem is , but i have been looking for hours and i cant seem to figure it out :-s
here's my code :
(main activity) XML Layout: :
<RelativeLayout "
android:id="#+id/texttoto"
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="com.toto.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/editText_mail"
android:layout_alignLeft="#+id/editText_mail"
android:onClick="test_trucs"
android:text="#string/test" />
<EditText
android:id="#+id/txttopass"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="15dp"
android:ems="10"
android:hint="#string/texttopass" >
</EditText>
</RelativeLayout>
**(second activity) XML Layout:* :*
<RelativeLayout "
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="com.toto.Blabla$PlaceholderFragment" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>
****MainActivity.JAVA:****
package com.toto;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "com.toto.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
/** mettre les class ICI **/
public void test_trucs(View view) {
Intent intent = new Intent(this, Blabla.class);
EditText editText = (EditText) findViewById(R.id.txttopass);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
****Blabla.JAVA:****
package com.toto;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class Blabla extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_blabla);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView1 = new TextView(this);
textView1.setTextSize(40);
textView1.setText(message);
// Set the text view as the activity layout
setContentView(textView1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.blabla, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_blabla,
container, false);
return rootView;
}
}
}
the logcat show this :
06-19 15:35:47.982: E/AndroidRuntime(22378): FATAL EXCEPTION: main
06-19 15:35:47.982: E/AndroidRuntime(22378): Process: com.toto, PID: 22378
06-19 15:35:47.982: E/AndroidRuntime(22378): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.toto/com.toto.Blabla}: java.lang.NullPointerException
06-19 15:35:47.982: E/AndroidRuntime(22378): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
06-19 15:35:47.982: E/AndroidRuntime(22378): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
06-19 15:35:47.982: E/AndroidRuntime(22378): at android.app.ActivityThread.access$800(ActivityThread.java:135)
06-19 15:35:47.982: E/AndroidRuntime(22378): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
06-19 15:35:47.982: E/AndroidRuntime(22378): at android.os.Handler.dispatchMessage(Handler.java:102)
06-19 15:35:47.982: E/AndroidRuntime(22378): at android.os.Looper.loop(Looper.java:136)
06-19 15:35:47.982: E/AndroidRuntime(22378): at android.app.ActivityThread.main(ActivityThread.java:5001)
06-19 15:35:47.982: E/AndroidRuntime(22378): at java.lang.reflect.Method.invokeNative(Native Method)
06-19 15:35:47.982: E/AndroidRuntime(22378): at java.lang.reflect.Method.invoke(Method.java:515)
06-19 15:35:47.982: E/AndroidRuntime(22378): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
06-19 15:35:47.982: E/AndroidRuntime(22378): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
06-19 15:35:47.982: E/AndroidRuntime(22378): at dalvik.system.NativeStart.main(Native Method)
06-19 15:35:47.982: E/AndroidRuntime(22378): Caused by: java.lang.NullPointerException
06-19 15:35:47.982: E/AndroidRuntime(22378): at com.toto.Blabla.onCreate(Blabla.java:39)
06-19 15:35:47.982: E/AndroidRuntime(22378): at android.app.Activity.performCreate(Activity.java:5231)
06-19 15:35:47.982: E/AndroidRuntime(22378): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
06-19 15:35:47.982: E/AndroidRuntime(22378): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
06-19 15:35:47.982: E/AndroidRuntime(22378): ... 11 more
i know this is probably the newbiest thing ever, but please be indulgent ..
thanks in advance for the help !
You are calling setContentView twice, the first:
setContentView(R.layout.activity_blabla);
Isn't in the tutorial. I'm not sure what's exactly causing the NullPointer exception, but it seems that calling that twice can cause problems.
If you want to use a more complex layout (R.layout_blabla), and show the message, like it seems to be your case as the text view is in that layout, reference it from the onCreate by findViewById, instead of create a new TextView
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_blabla);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView1 = (TextView)findViewById(R.id.textView1)
textView1.setTextSize(40);
textView1.setText(message);
// Set the text view as the activity layout
setContentView(textView1);
}
Related
I have two Fragments. First Fragment is named as Fragment1 and Second Fragment named as physics. First Fragment have Two Buttons. I would Like to show a local html page ( say A.html when Button1 is pressed and B.html when Button2 is Pressed ) in Second Fragment i.e in physics.java
My Fragment.java contains following code
package com.nepalpolice.mnemonics;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
/**
* Created by Sagar on 2017/09/23.
*/
public class Fragment1 extends Fragment implements View.OnClickListener{
public Button button;
public Fragment1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_fragment1, container, false);
button = (Button) view.findViewById(R.id.button1);
button = (Button) view.findViewById(R.id.button2);
return view;
}
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity().getApplicationContext(), physics.class);
switch (v.getId()) {
case R.id.button1:
intent.putExtra("url", "file:///android_asset/B.html");
startActivity(intent);
break;
case R.id.button2:
intent.putExtra("url", "file:///android_asset/A.html");
startActivity(intent);
break;
default:
break;
}
}
}
and My SecondFragment contains following code
package com.nepalpolice.mnemonics;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
/**
* Created by Sagar on 2017/09/23.
*/
public class physics extends Fragment {
WebView myWebView;
public physics() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_fragment2, container, false);
String url = getActivity().getIntent().getStringExtra("url");
myWebView=(WebView)rootView.findViewById(R.id.webview);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.loadUrl(url);
myWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
});
return rootView;
}
}
and main fragment_fragment1.xml contains
<FrameLayout 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"
tools:context="com.nepalpolice.mnemonics.Fragment1">
<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" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_alignParentTop="true"
android:text="button01"
android:onClick="onClick"/>
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_alignParentTop="true"
android:text="button02"
android:onClick="onClick"/>
</LinearLayout>
</FrameLayout>
and Secondfragment.xml has
<?xml version="1.0" encoding="utf-8"?>
<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" >
<WebView
android:id="#+id/webview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
But my is Crashing with following Error.
java.lang.IllegalStateException: Could not find method onClick(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'button1'
I'm almost Done with my project. If it could be done...It would mean a lot for me.
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return FirstFragment.newInstance("FirstFragment, Instance 1");
case 1: return SecondFragment.newInstance("SecondFragment, Instance 1");
case 2: return ThirdFragment.newInstance("ThirdFragment, Instance 1");
case 3: return ThirdFragment.newInstance("ThirdFragment, Instance 2");
case 4: return ThirdFragment.newInstance("ThirdFragment, Instance 3");
default: return ThirdFragment.newInstance("ThirdFragment, Default");
}
}
#Override
public int getCount() {
return 5;
}
}
}
I am getting a type mismatch error. Basically it says it cannot convert the activity to a fragment. from what I have read it has something to do with my imports. Can anyone help me out?
I know its late but am submitting this answer because it happens with a lot of developers.
This error appears due to library import conflict. Check your imports in FirstFragment, SecondFragment and ThirdFragment and make sure that you are using the same fragment library.
if you are using Fragments for older APIs you need to import android.support.v4.app.Fragment;
But if you are using Fragments for newer APIs use
android.app.Fragment;
The problem comes when you use auto-complete to complete class name you may not notice what library you are importing.
Please look at the code below. I show you and I expand you how to create pager view:
MainActivity class:
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
}
}
activity_main.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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<!-- it is important to use ViewPager from support library -->
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
MyPagerAdapter.class
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
public class MyPagerAdapter extends FragmentStatePagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
switch (pos) {
case 0:
return FirstFragment.newInstance("FirstFragment, Instance 1");
case 1:
return SecondFragment.newInstance("SecondFragment, Instance 1");
case 2:
return ThirdFragment.newInstance("ThirdFragment, Instance 1");
case 3:
return ThirdFragment.newInstance("ThirdFragment, Instance 2");
case 4:
return ThirdFragment.newInstance("ThirdFragment, Instance 3");
default:
return ThirdFragment.newInstance("ThirdFragment, Default");
}
}
#Override
public int getCount() {
return 5;
}
}
fragment_layout.xml
I created common layout for all fragments. I will change background colour and set text in source code below.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"/>
</RelativeLayout>
FirstFragment.class
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class FirstFragment extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.fragment_layout, container, false);
v.setBackgroundColor(Color.RED);
TextView textView = (TextView) v.findViewById(R.id.text_view);
textView.setText(getArguments().getString("value"));
return v;
}
public static FirstFragment newInstance(String s) {
Bundle args = new Bundle();
args.putString("value", s);
FirstFragment result = new FirstFragment();
result.setArguments(args);
return result;
}
}
SecondFragment.class
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class SecondFragment extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.fragment_layout, container, false);
v.setBackgroundColor(Color.GRAY);
TextView textView = (TextView) v.findViewById(R.id.text_view);
textView.setText(getArguments().getString("value"));
return v;
}
public static SecondFragment newInstance(String s) {
Bundle args = new Bundle();
args.putString("value", s);
SecondFragment result = new SecondFragment();
result.setArguments(args);
return result;
}
}
ThirdFragment.class
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class ThirdFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_layout, container, false);
v.setBackgroundColor(Color.BLUE);
TextView textView = (TextView) v.findViewById(R.id.text_view);
textView.setText(getArguments().getString("value"));
return v;
}
public static ThirdFragment newInstance(String s) {
Bundle args = new Bundle();
args.putString("value", s);
ThirdFragment result = new ThirdFragment();
result.setArguments(args);
return result;
}
}
Here is complete program witch display 5 fragment with text which is passed as parameter. Please try it. If you have one more question or something in my solution is not clear or my solution is not helpful for you. Go ahead, just ask. :)
i have placed a textview and a toggle button into a list view by using the following xml file and i have used an arrayadapter to set it on to my layout, my problem is when i scroll down in the list view by unchecking a few toggle buttons (which are all set to be checked by default), they go back to default state and few others change state. As i want to fetch the state of the toggle button in my later stages its very important to stick on to the state that ive assigned to the toggle button. Please help to resolve this problem. Here are my xml file and the java code i use to set it on to the adapter. thank you in prior...
xml file that is named listdecor is included here
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/lvlistdecor"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#000000"
android:orientation="horizontal"
android:weightSum="2" >
<TextView
android:id="#+id/tvlistdecor"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1.5"
android:ellipsize="marquee"
android:singleLine="true"
android:text="sample"
android:textColor="#FFFFFF"
android:textSize="24sp"
android:typeface="sans" />
<CheckBox
android:id="#+id/cbusn_checked"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="6sp"
android:layout_weight="0.5"
android:checked="true"
android:focusable="false"
android:padding="10dp" />
</LinearLayout>
Sir i made certain changes and also included the custom adapter to the listview and also changed to CheckBox instead of toggle buttons. but now the entire list view is not visible on my emulator. i've included my edited java class and xml file, please suggest me the changes, thank you...
The modified java code is included here
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); // Setting the window to full screen Step 1
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN); // Setting the window to full screen Step 2
setContentView(R.layout.attendance5);
facid = (TextView) findViewById(R.id.tvfacid);
facname = (TextView) findViewById(R.id.tvfacname);
subjectchosen = (TextView) findViewById(R.id.tvsubject);
// llattendlist = (LinearLayout)findViewById(R.id.llattendlist);
String Uid = getIntent().getStringExtra("Uid");
facid.setText(Uid);
String Name = getIntent().getStringExtra("Name");
facname.setText(Name);
String Sub = getIntent().getStringExtra("Sub");
subjectchosen.setText(Sub);
Attendusn = getIntent().getExtras();
if(Attendusn!=null)
{
AttendStud_usn = (ArrayList<String>)Attendusn.getStringArrayList("AttendStud_usn");
}
String AttendLen = String.valueOf(AttendStud_usn.size());
//int flag = 0 ;
//subjectchosen.setText(String.valueOf(AttendStud_usn));
myListView = (ListView) findViewById(R.id.lvnames);
// myListView.setAdapter(new ArrayAdapter<String>(this, R.layout.listdecoration,R.id.tvlistdecor, AttendStud_usn));
//ArrayAdapter<String> MyAdapter= new ArrayAdapter<String>(this,R.layout.listdecoration, R.id.tvlistdecor,AttendStud_usn);
//myListView.setAdapter(MyAdapter);
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View item, int position,
long id) {
// TODO Auto-generated method stub
Stud_usn usn= MyAdapter.getItem(position);
usn.toggleChecked();
Stud_usnViewHolder vh_usn= (Stud_usnViewHolder) item.getTag();
vh_usn.getCheckBox().setChecked(usn.isChecked());
}
});
MyAdapter = new Stud_Adapter(this,AttendStud_usn);
myListView.setAdapter(MyAdapter);
}
private static class Stud_usn{
private String usn_no="";
private boolean checked=true;
public Stud_usn(String usn_no){
this.usn_no = usn_no;
}
public String getUsn(){
return usn_no;
}
public void setChecked(boolean checked){
this.checked=checked;
}
public Object isChecked() {
// TODO Auto-generated method stub
return checked;
}
public String toString(){
return usn_no;
}
public void toggleChecked() {
// TODO Auto-generated method stub
checked = !checked;
}
}
private static class Stud_usnViewHolder{
private CheckBox checkbox;
private TextView textview;
public Stud_usnViewHolder(TextView textview, CheckBox checkbox){
this.checkbox=checkbox;
this.textview=textview;
}
public CheckBox getCheckBox() {
// TODO Auto-generated method stub
return checkbox;
}
public TextView getTextView(){
return textview;
}
}
private static class Stud_Adapter extends ArrayAdapter<Stud_usn>{
public LayoutInflater inflater;
public Stud_Adapter(Context context, List<String> attendStud_usn) {
super(context,R.layout.listdecoration,R.id.tvlistdecor);
// TODO Auto-generated constructor stub
inflater = LayoutInflater.from(context);
}
public View getView(int position, View convertView, ViewGroup parent){
Stud_usn usn = (Stud_usn) this.getItem(position);
CheckBox checkbox;
TextView textview;
if(convertView == null){
convertView = inflater.inflate(R.layout.listdecoration,null);
textview = (TextView) convertView.findViewById(R.id.tvlistdecor);
checkbox = (CheckBox) convertView.findViewById(R.id.cbusn_checked);
}
return convertView;
}
}
}
The view objects are recycled. You have to store that info sepperately. Not in the view but in the with the data you use in the adapter. When generating the views use this info to set the button state again.
You have to implement a custom adapter. Use the BaseAdapter class.
I am new to android ,I want make an app which needs a progress bar, but the code which I wrote seems to crash each time I run it .As till now I am unable to find the bug.I am using a vertical progress bar.
thanx in advance.
package com.example.progtask;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
public class MainActivity extends Activity implements OnClickListener, Runnable {
private ProgressBar pb;
private Button show;
private Button hide;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pb = (ProgressBar) findViewById(R.id.progressBar1);
show = (Button) findViewById(R.id.button1);
hide = (Button) findViewById(R.id.hide);
// pb.setVisibility(ProgressBar.GONE);
show.setOnClickListener(this);
hide.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.equals(show)) {
pb.setVisibility(ProgressBar.VISIBLE);
pb.setProgress(0);
pb.setMax(12);
new Thread(this).start();
} else {
pb.setVisibility(ProgressBar.GONE);
}
}
#Override
public void run() {
// TODO Auto-generated method stub
int n = 0;
while (n < 10) {
n++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
pb.setProgress(n);
}
}
Below is the Xml file
<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" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="#dimen/padding_medium"
android:text="picelate"
tools:context=".MainActivity" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="82dp"
android:layout_toLeftOf="#+id/textView1"
android:text="show" />
<Button
android:id="#+id/hide"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button1"
android:layout_alignBottom="#+id/button1"
android:layout_toRightOf="#+id/textView1"
android:text="hide" />
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/textView1"
android:layout_alignParentLeft="true" />
</RelativeLayout>
Try this
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.button1:
pb.setVisibility(ProgressBar.VISIBLE);
pb.setProgress(0);
pb.setMax(12);
new Thread(this).start();
break;
case R.id.hide:
// do the needful.
break;
}
}
This is how it worked:
public class MainActivity extends Activity implements OnClickListener, Runnable {
private ProgressBar pb;
private Button show;
private Button hide;
int n;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pb = (ProgressBar) findViewById(R.id.progressBar1);
show = (Button) findViewById(R.id.button1);
hide = (Button) findViewById(R.id.button2);
// pb.setVisibility(ProgressBar.GONE);
show.setOnClickListener(this);
hide.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId())
{
case R.id.button1:
pb.setVisibility(ProgressBar.VISIBLE);
pb.setProgress(0);
pb.setMax(100);
n = 0;
new Thread(this).start();
break;
case R.id.button2:
// do the needful.
pb.setVisibility(ProgressBar.GONE);
break;
}
}
#Override
public void run() {
// TODO Auto-generated method stub
int n = 0;
while (n < 100) {
n++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}pb.setProgress(n*10);
}
pb.setProgress(n*10);
}
}
the xml file is:
<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" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="show" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="hide" />
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:progressDrawable="#drawable/progbar"
android:layout_gravity="bottom"
/>
</LinearLayout>
I am trying to get the values clicked on my listactivity to display on the third.xml. it has 4 editText fields. I want to display the 4 columns on the 4 ET fields. HELP!!!
HEre is a code for getting a specific record in my DBAdapter:
public Cursor getRecord(long rowId) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE, new String[] {ROW_ID,
KEY_FIRSTNAME, KEY_LASTNAME, KEY_CITY, KEY_STATE},
ROW_ID + "=" + rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
Then here is my Second.java list acitivity
package com.dtan.testcontacts;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;
public class Second extends ListActivity {
public final static String ID_EXTRA="com.dtan.testcontacts._ID";
DBAdapter db = new DBAdapter(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db.open();
Cursor c = db.getAllContacts();
ArrayList<String> columns = new ArrayList<String>();
int iFirstName = c.getColumnIndex(DBAdapter.KEY_FIRSTNAME);
int iLastName = c.getColumnIndex(DBAdapter.KEY_LASTNAME);
for(c.move(0); c.moveToNext(); c.isAfterLast()){
String columnstring = c.getString(iFirstName)+ " " + c.getString(iLastName)+"\n";
columns.add(columnstring);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, columns);
setListAdapter(adapter);
final ListView lv = getListView();
registerForContextMenu(lv);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.contextmenu, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch(item.getItemId()){
case R.id.delete:
AlertDialog.Builder abuilder = new AlertDialog.Builder(Second.this);
abuilder.setMessage("Are you sure you want to delete?");
abuilder.setCancelable(false);
abuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Cursor c = db.getAllContacts();
c.moveToPosition(info.position);
String id = c.getString(c.getColumnIndex(DBAdapter.ROW_ID));
db.open();
db.deleteContact(Long.parseLong(id));
c.close();
Toast toast = Toast.makeText(Second.this, "Contact Deleted Successfully", 5000);
toast.show();
Intent i = new Intent(Second.this, Second.class);
startActivity(i);
}
});
abuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = abuilder.create();
alert.show();
return true;
case R.id.edit:
getListView().setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> lv, View cell,
int position, long id) {
Intent i = new Intent(Second.this, Third.class);
i.putExtra("entry_id", position);
startActivity(i);
}
});
}
return super.onContextItemSelected(item);
}
}
Finally, here is the Third activity where i want to display the value clicked on the listactivity to display on each edittext. xml first then java code:
<EditText
android:id="#+id/editText1Third"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_marginTop="20dp"
android:clickable="false"
android:ems="10"
android:hint="Firstname"
android:inputType="text"
android:text="#string/none" />
<TextView
android:id="#+id/textView1"
android:layout_width="110dp"
android:layout_height="wrap_content"
android:text="#string/fname" />
<EditText
android:id="#+id/editText2Third"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_marginTop="20dp"
android:ems="10"
android:hint="Lastname"
android:inputType="text"
android:text="#string/none" />
<TextView
android:id="#+id/textView2"
android:layout_width="74dp"
android:layout_height="wrap_content"
android:text="#string/lastname" />
<EditText
android:id="#+id/editText3Third"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_marginTop="20dp"
android:ems="10"
android:hint="City"
android:inputType="text"
android:text="#string/none" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/city" />
<EditText
android:id="#+id/editText4Third"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_marginTop="20dp"
android:ems="10"
android:hint="State"
android:inputType="text"
android:text="#string/none" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/state" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="64dp" >
<Button
android:id="#+id/ButtonUpdateThird"
android:layout_width="100dp"
android:layout_height="60dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:gravity="center"
android:text="#string/update" />
</RelativeLayout>
</LinearLayout>
Third.java
package com.dtan.testcontacts;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.EditText;
public class Third extends Activity {
private DBAdapter db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.third);
int b = this.getIntent().getExtras().getInt("entry_id");
EditText firstname = (EditText) findViewById(R.id.editText1Third);
db.open();
Cursor c = db.getRecord(b);
firstname.setText(c.getString(1));
db.close();
}
}