I want to try to save multiple EditText input to a txt file. I also want the button to intent to another activity. I've try to implement the code but my apps crash when i click the button.
This is my code.
MainActivity.Java:
public class MainActivity extends AppCompatActivity {
EditText name, numbTent, pangkat, date, time, penyelia, pegawai;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText) findViewById(R.id.name);
numbTent = (EditText) findViewById(R.id.numbTent);
pangkat = (EditText) findViewById(R.id.pangkat);
date = (EditText) findViewById(R.id.date);
time = (EditText) findViewById(R.id.time);
penyelia = (EditText) findViewById(R.id.penyelia);
pegawai = (EditText) findViewById(R.id.pegawai);
}
public void SaveInfo(View v) {
String state;
state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state))
{
File Root = Environment.getExternalStorageDirectory();
File Dir = new File(Root.getAbsolutePath()+"/Semak Operasi Mampatan SRC");
if(Dir.exists())
{
Dir.mkdir();
}
File file = new File(Dir,"AttendantInfo.txt");
String Info1 = name.getText().toString();
String Info2 = numbTent.getText().toString();
String Info3 = pangkat.getText().toString();
String Info4 = date.getText().toString();
String Info5 = time.getText().toString();
String Info6 = penyelia.getText().toString();
String Info7 = pegawai.getText().toString();
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(Info1.getBytes());
fileOutputStream.write(Info2.getBytes());
fileOutputStream.write(Info3.getBytes());
fileOutputStream.write(Info4.getBytes());
fileOutputStream.write(Info5.getBytes());
fileOutputStream.write(Info6.getBytes());
fileOutputStream.write(Info7.getBytes());
fileOutputStream.close();
name.setText("");
numbTent.setText("");
pangkat.setText("");
date.setText("");
time.setText("");
penyelia.setText("");
pegawai.setText("");
Toast.makeText(getApplicationContext(),"Info Saved",Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
else
{
Toast.makeText(getApplicationContext(),"Storage not found",Toast.LENGTH_LONG).show();
}
}
Intent i=new Intent(MainActivity.this,ChecklistType.class);
startActivity(i);
}
activitymain.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
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.example.hp.semakoperasimampatansrc.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/title"
android:gravity="center"
android:textSize="26sp"
android:textStyle="bold"
android:id="#+id/title"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:id="#+id/name"
android:hint="#string/nama"
android:layout_marginTop="30dp"
android:layout_below="#+id/title"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="text"
android:id="#+id/pangkat"
android:layout_below="#+id/numbTent"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="#string/pangkat" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:id="#+id/penyelia"
android:layout_below="#+id/date"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="#string/penyelia" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:id="#+id/pegawai"
android:layout_below="#+id/penyelia"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="#string/pegawai" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:id="#+id/numbTent"
android:hint="#string/NumTent"
android:layout_below="#+id/name"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="time"
android:ems="10"
android:id="#+id/editText"
android:hint="#string/time"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="datetime"
android:id="#+id/date"
android:hint="#string/date"
android:layout_below="#+id/pangkat"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="#+id/editText"
android:layout_toStartOf="#+id/editText" />
<Button
android:id="#+id/title_submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/title_submit"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="10dp"
android:layout_marginEnd="10dp"
android:layout_marginBottom="10dp"
android:onClick="SaveInfo"/>
Perhaps this block is wrong :
if(Dir.exists())
{
Dir.mkdir();
}
What you want is if the directory doesn't exist,make it.So when you new .txt file ,it crashes.
if(!Dir.exists())
{
Dir.mkdir();
}
On Android 6.0 and above, the WRITE_EXTERNAL_STORAGE needs to be requested to the user. So you need to check if your application has the permission at startup to avoid your app crash. Something like:
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Log.v(TAG,"Permission is granted");
//File write logic here
return true;
}
And if not, then you can request for the permissiong using:
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
This will show a permission request dialog to the user and the user can decide whether or not to allow your application to have the permission.
You can perform desired actions depending upon the result of the permission request in the following function.
#Override
public void onRequestPermissionsResult(int requestCode, String [] permissions, int [] grantResults) {
switch (requestCode) {
case REQUEST_CODE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted. Write file logic
} else {
// permission denied
}
return;
}
}
}
Related
So I am creating an android application which opens the url entered by the user. Now each time an url is entered by the user, it needs to be save using the "save" button and the save list is seen using the "list" button.
This is my Interface:
This is my xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/content_main"
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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.application.mota_app.MainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:text="#string/enter_the_url_below"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/enter_URL"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="26dp"
android:textSize="19sp"
android:textColor="#android:color/holo_green_dark" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/txtbox_website"
android:layout_marginTop="18dp"
android:width="300dp"
android:inputType="textUri"
android:layout_below="#+id/enter_URL"
android:layout_centerHorizontal="true" />
<Button
android:text="#string/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_save"
android:textColor="#color/colorAccent"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:text="#string/visit"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="#+id/btn_visit"
android:textColor="#android:color/holo_blue_dark"
android:onClick="open"
android:layout_marginBottom="50dp"
android:layout_alignBottom="#+id/btn_save"
android:layout_centerHorizontal="true" />
<Button
android:text="#string/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_list"
android:textColor="?android:attr/colorPressedHighlight"
android:layout_below="#+id/btn_save"
android:layout_alignLeft="#+id/btn_save"
android:layout_alignStart="#+id/btn_save" />
</RelativeLayout>
So I am stuck in the save and list. I am using shared preferences, but I am not able to save and list the URLS. This is the code I wrote:
public class MainActivity extends AppCompatActivity {
public static final String MY_EMP_PREFS = "MyPrefs";
private EditText url;
private Button save;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
url = (EditText)findViewById(R.id.txtbox_website);
save = (Button)findViewById(R.id.btn_save);
}
public void open(View view){
if (url.getText().toString().matches("")) {
Toast.makeText(getApplicationContext(), "Enter a website to open!", Toast.LENGTH_SHORT).show();
return;
}
if (!url.getText().toString().startsWith("http://") && !url.getText().toString().startsWith("https://"))
{
url.setText("http://" + url.getText().toString());
}
if (!Patterns.WEB_URL.matcher(url.getText().toString()).matches())
{
Toast.makeText(getApplicationContext(), "Invalid URL!", Toast.LENGTH_SHORT).show();
url.setError("Enter a valid URL");
url.setText("");
url.setSelection(0);
return;
}
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url.getText().toString()));
startActivity(browserIntent);
}
public void save(View view) {
SharedPreferences pref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
// We need an editor object to make changes
SharedPreferences.Editor edit = pref.edit();
// Set/Store data
edit.putString("save", url.getText().toString());
// Commit the changes
edit.commit();
Toast.makeText(getApplicationContext(), "URL Saved", Toast.LENGTH_SHORT).show();
}
Where am I going wrong? What should I do?
Thanks
You have to add the method reference in your Widget:
<Button
android:text="#string/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_save"
android:onClick="save" //HERE
android:textColor="#color/colorAccent"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
Also, when you use a SharedPreferences, you are putting a String value using the key "save". So when you click on save button, you are overriding the old value and put a new value in the place.
To solve this issue, I think the best solution is use a Framework to persist the data and list it after.
edit.putString("save", url.getText().toString()); //here you are overriding the vlaue
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
When i click my button in my activity, it will stop and show an error like this :
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
In my activity, i put button.setOnclickListener in onResponse() method from Response.Listener. I do this because i want to get the data from JSONObject and use that data when i click my button.
Sorry, I'm not too fluent in English :)
My activity code:
public class MenuDaftarNilai2 extends AppCompatActivity {
TextView tvMatkulDN, tvKlpDN, tvMhsDN;
Button bUasDN;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_daftar_nilai2);
tvMatkulDN = (TextView) findViewById(R.id.tvMatkulDN) ;
tvKlpDN = (TextView) findViewById(R.id.tvKlpDN) ;
tvMhsDN = (TextView) findViewById(R.id.tvMhsDN) ;
bUasDN = (Button) findViewById(R.id.bUasDN) ;
Intent intent = getIntent();
final String nama_matkul = intent.getStringExtra("nama_matkul");
final String nama_klp = intent.getStringExtra("nama_klp");
final String nama_mhs = intent.getStringExtra("nama_mhs");
tvMatkulDN.setText(nama_matkul);
tvKlpDN.setText(nama_klp);
tvMhsDN.setText(nama_mhs);
Response.Listener responseListener1 = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
final String nilai_uas = jsonResponse.getString("nilai_uas");
final String id_uas = jsonResponse.getString("id_uas");
bUasDN.setText("Nilai Uas : " + nilai_uas);
bUasDN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MenuDaftarNilai2.this, EditUas.class);
intent.putExtra("nilai_uas", nilai_uas);
intent.putExtra("nama_matkul", nama_matkul);
intent.putExtra("nama_klp", nama_klp);
intent.putExtra("nama_mhs", nama_mhs);
intent.putExtra("id_uas", id_uas);
MenuDaftarNilai2.this.startActivity(intent);
finish();
}
});
}catch (JSONException e) {
e.printStackTrace();
}
}
};
ResponUas resUas = new ResponUas(nama_klp,nama_mhs, responseListener1);
RequestQueue queue1 = Volley.newRequestQueue(MenuDaftarNilai2.this);
queue1.add(resUas);
My XML code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".LoginAsis.MenuAsisten.MenuDaftarNilai.MenuDaftarNilai2"
android:background="#ad4f4f">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nama Mata Kuliah"
android:id="#+id/textView54"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textColor="#ffffff" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nama Kelompok"
android:id="#+id/textView58"
android:layout_alignParentStart="true"
android:layout_below="#+id/textView54"
android:layout_alignParentLeft="true"
android:textColor="#ffffff" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nama Mahasiswa"
android:id="#+id/textView59"
android:layout_alignParentStart="true"
android:layout_below="#+id/textView58"
android:layout_alignParentLeft="true"
android:textColor="#ffffff" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=":"
android:id="#+id/textView60"
android:textColor="#ffffff"
android:layout_alignParentTop="true"
android:layout_alignLeft="#+id/textView61"
android:layout_alignStart="#+id/textView61" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=":"
android:id="#+id/textView61"
android:textColor="#ffffff"
android:layout_below="#+id/textView60"
android:layout_alignLeft="#+id/textView62"
android:layout_alignStart="#+id/textView62" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=":"
android:id="#+id/textView62"
android:textColor="#ffffff"
android:layout_marginLeft="68dp"
android:layout_marginStart="40dp"
android:layout_below="#+id/textView61"
android:layout_toRightOf="#+id/textView54"
android:layout_toEndOf="#+id/textView54" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:id="#+id/tvMatkulDN"
android:layout_alignTop="#+id/textView60"
android:layout_toRightOf="#+id/textView60"
android:textColor="#ffffff"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:id="#+id/tvKlpDN"
android:layout_below="#+id/tvMatkulDN"
android:layout_toRightOf="#+id/textView60"
android:textColor="#ffffff"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:id="#+id/tvMhsDN"
android:layout_below="#+id/tvKlpDN"
android:layout_toRightOf="#+id/textView61"
android:textColor="#ffffff"
android:layout_alignRight="#+id/tvKlpDN"
android:layout_alignEnd="#+id/tvKlpDN"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Belum ada nilai uas"
android:id="#+id/bUasDN"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_below="#id/textView59"
android:gravity="left|center_vertical"
android:drawableRight="#drawable/ic_create_black_24dp"/>
</RelativeLayout>
just put this outside the response parenthesis ...............
bUasDN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MenuDaftarNilai2.this, EditUas.class);
intent.putExtra("nilai_uas", nilai_uas);
intent.putExtra("nama_matkul", nama_matkul);
intent.putExtra("nama_klp", nama_klp);
intent.putExtra("nama_mhs", nama_mhs);
intent.putExtra("id_uas", id_uas);
MenuDaftarNilai2.this.startActivity(intent);
finish();
}
});
enjoy coding..........
I just do my project but when I test my app I found that then I touch the screen by using more than one fingers my app may start two or three different activities.
The activities all go to the back stack. Is this a bug in Android framework? But I can't reappear this condition, it just happened.
So, have you guys ever have this problem? Please come and discuss with me. If you do; Thanks.
Supply:
And here is My xml file , when I click the different RelativeLayout at the same time , it happened.
I tried this afternoon , but this condition is not appear anymore. Now I am confusing.
<LinearLayout android:layout_width="match_parent"
android:orientation="vertical"
android:background="#color/appDefaultSingleBlockBackground"
android:layout_height="wrap_content">
<RelativeLayout android:layout_width="match_parent"
android:layout_height="100dp"
android:clickable="true"
android:background="#drawable/mine_bg"
android:id="#+id/mine_goto_personal_info_btn"
>
<TextView android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_centerVertical="true"
android:gravity="center_vertical"
android:id="#+id/mine_nick_and_avatar"
android:drawablePadding="10dp"
android:layout_marginLeft="15dp"
style="#style/TextTitle"
android:textColor="#color/appDefaultSingleBlockBackground"
android:text=""/>
<ImageView android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="#drawable/venue_maxbutton"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_marginRight="15dp"
/>
</RelativeLayout>
<RelativeLayout android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/appDefaultSingleBlockBackground"
android:clickable="true"
android:id="#+id/mine_goto_interesting_venue"
>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:gravity="center_vertical"
android:drawablePadding="10dp"
android:layout_marginLeft="15dp"
style="#style/TextNomal"
android:drawableLeft="#drawable/information_attentionbutton"
android:text="#string/myAtentionVenue"/>
<ImageView android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="#drawable/venue_maxbutton"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_marginRight="15dp"
/>
</RelativeLayout>
<View android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#color/dividerdefault"
/>
<RelativeLayout android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/appDefaultSingleBlockBackground"
android:clickable="true"
android:id="#+id/mine_goto_setting"
>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:gravity="center_vertical"
android:drawablePadding="10dp"
android:layout_marginLeft="15dp"
style="#style/TextNomal"
android:drawableLeft="#drawable/information_setbutton"
android:text="#string/setting"/>
<ImageView android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="#drawable/venue_maxbutton"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_marginRight="15dp"
/>
</RelativeLayout>
<View android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#color/dividerdefault"
/>
<RelativeLayout android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/appDefaultSingleBlockBackground"
android:clickable="true"
android:id="#+id/mine_goto_youhuijuan"
>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:gravity="center_vertical"
android:drawablePadding="10dp"
android:layout_marginLeft="15dp"
style="#style/TextNomal"
android:drawableLeft="#drawable/information_discountbutton"
android:text="#string/youhuijuan"/>
<ImageView android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="#drawable/venue_maxbutton"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_marginRight="15dp"
/>
</RelativeLayout>
<View android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#color/dividerdefault"
/>
<RelativeLayout android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/appDefaultSingleBlockBackground"
android:clickable="true"
android:id="#+id/mine_goto_my_rest_money"
>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:gravity="center_vertical"
android:drawablePadding="10dp"
android:layout_marginLeft="15dp"
style="#style/TextNomal"
android:drawableLeft="#drawable/information_balancebutton"
android:text="#string/myRest"/>
<ImageView android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="#drawable/venue_maxbutton"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_marginRight="15dp"
/>
</RelativeLayout>
<View android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#color/dividerdefault"
/>
<RelativeLayout android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/appDefaultSingleBlockBackground"
android:clickable="true"
android:id="#+id/mine_goto_secure"
>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:gravity="center_vertical"
android:drawablePadding="10dp"
android:layout_marginLeft="15dp"
style="#style/TextNomal"
android:drawableLeft="#drawable/information_accountssafebutton"
android:text="#string/secure"/>
<ImageView android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="#drawable/venue_maxbutton"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_marginRight="15dp"
/>
</RelativeLayout>
<View android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/dividerdefault"
/>
</LinearLayout>
and this is my java code .
private void init(View ret) {
final TextView txtAvatar = (TextView) ret.findViewById(R.id.mine_nick_and_avatar);
final RelativeLayout gotoPersonal = (RelativeLayout) ret.findViewById(R.id.mine_goto_personal_info_btn);
RelativeLayout gotoInterest = (RelativeLayout) ret.findViewById(R.id.mine_goto_interesting_venue);
RelativeLayout gotoSetting = (RelativeLayout) ret.findViewById(R.id.mine_goto_setting);
RelativeLayout gotoYouhuijuan = (RelativeLayout) ret.findViewById(R.id.mine_goto_youhuijuan);
RelativeLayout gotoMyRestMoney = (RelativeLayout) ret.findViewById(R.id.mine_goto_my_rest_money);
RelativeLayout gotoSecure = (RelativeLayout) ret.findViewById(R.id.mine_goto_secure);
gotoPersonal.setTag("gotoPersonal");
gotoInterest.setTag("gotoInterest");
gotoSetting.setTag("gotoSetting");
gotoYouhuijuan.setTag("gotoYouhuijuan");
gotoMyRestMoney.setTag("gotoMyRestMoney");
gotoSecure.setTag("gotoSecure");
try {
Object o = SharedPreferenceUtils.readInfo(mActivity, ConstData.UserInfo[1]);
if (o != null && !"null".equals(o)) {
txtAvatar.setText((String) o);
} else {
o = SharedPreferenceUtils.readInfo(mActivity, ConstData.UserInfo[10]);
if (o != null && !"null".equals(o))
txtAvatar.setText("KD" + o);
}
} catch (Exception e) {
}
Object o1 = SharedPreferenceUtils.readInfo(mActivity, ConstData.UserInfo[2]);
if (o1 != null)
MyApplication.downloader.download("http://" + o1, new ImageDownloadStateListener() {
#Override
public void loading() {
}
#Override
public void loadSuccess(Bitmap bitmap, String url) {
try {
bitmap = Tools.transforCircleBitmap(bitmap);
BitmapDrawable drawable = new BitmapDrawable(getResources(), bitmap);
gotoPersonal.measure(0, 0);
int measuredHeight = gotoPersonal.getMeasuredHeight();
LogHelper.print("==height" + measuredHeight);
drawable.setBounds(0, 0, measuredHeight / 5 * 4, measuredHeight / 5 * 4);
txtAvatar.setCompoundDrawables(drawable, null, null, null);
} catch (Exception e) {
//no nothing
}
}
#Override
public void loadFailed() {
}
});
gotoPersonal.setOnClickListener(this);
gotoInterest.setOnClickListener(this);
gotoSetting.setOnClickListener(this);
gotoYouhuijuan.setOnClickListener(this);
gotoMyRestMoney.setOnClickListener(this);
gotoSecure.setOnClickListener(this);
}
#Override
public void onResume() {
initActionBar();
super.onResume();
MobclickAgent.onPageStart(getClassName()); //统计页面
}
#Override
public void onPause() {
super.onPause();
MobclickAgent.onPageEnd(getClassName());
}
private String getClassName() {
String canonicalName = this.getClass().getCanonicalName();
String[] split = canonicalName.split("\\.");
return split[split.length - 1];
}
private void initActionBar() {
MyActivity activity = (MyActivity) mActivity;
activity.setActionBarLeftImg(new ColorDrawable(Color.TRANSPARENT), false);
activity.setActionBarRightImg(new ColorDrawable(Color.TRANSPARENT));
activity.setOnActionBarLeftClickListener(null);
activity.setOnActionBarRightClickListener(null);
activity.setActionBarTitle("个人中心");
}
#Override
public void onClick(View v) {
Object tag = v.getTag();
if (tag != null) {
String str = (String) tag;
if (mActivity == null) {
return;
}
if (!((MyActivity) (mActivity)).isLogin) {
Intent intent = new Intent(mActivity, LoginActivity.class);
startActivity(intent);
return;
}
if (!TextUtils.isEmpty(str))
if ("gotoPersonal".equals(str)) {
Intent intent = new Intent(mActivity, PersonalInfoActivity.class);
startActivity(intent);
} else if ("gotoInterest".equals(str)) {
Intent intent = new Intent(mActivity, VenueListActivity.class);
intent.putExtra("isInterests", true);
startActivity(intent);
} else if ("gotoSetting".equals(str)) {
Intent intent = new Intent(mActivity, SettingActivity.class);
startActivity(intent);
} else if ("gotoYouhuijuan".equals(str)) {
Intent intent = new Intent(mActivity, FavorableActivity.class);
startActivity(intent);
} else if ("gotoSecure".equals(str)) {
Intent intent = new Intent(mActivity, SecureActivity.class);
startActivity(intent);
} else if ("gotoMyRestMoney".equals(str)) {
Intent intent = new Intent(mActivity, MyRestActivity.class);
startActivity(intent);
}
}
}
You need to define the launch mode. There are at least two ways of solving this by either using the manifest file (hint: singleTop) or by using Intent flags (hint: FLAG_ACTIVITY_SINGLE_TOP).
Good luck!
Simpliest approach would be disable control that starts your Activity (button for example) after 1 click, and enable it later with some condition or action. Try it.
You can use this approach.......
((Button)findViewById(R.id.someButton)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
((Button)findViewById(R.id.someButton)).setEnabled(false);
}
});
Happy coding
In my project, im going to make a multiple choice type question. I can select the questions and answer from mysql, however, i cant do the "matching" of the answer between input answer and the data from mysql. I tried some solutions but they doesnt work as well. I need a big help on it. Below are my codes.
the java class that make multiple choice
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.normalmode);
new DataAsyncTask().execute();
}
public void onClick(View v){
inputtext = ((Button) v).getText().toString();
tv3 = (TextView)findViewById(R.id.textView3);
tv3.setText(inputtext);
if(inputtext == tv2.getText().toString()){
playerscore +=5;
} else {
playerscore +=1;
}
score.setText("Scores : " + playerscore);
new DataAsyncTask().execute();
}
class DataAsyncTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... param) {
String result = DBConnector.executeQuery("SELECT * FROM questions ORDER BY RAND( ) LIMIT 1");
return result;
}
#Override
protected void onPostExecute(String result) {
question = (TextView)findViewById(R.id.textView_question);
fchoice = (Button)findViewById(R.id.Btn_choice1);
schoice = (Button)findViewById(R.id.Btn_choice2);
tchoice = (Button)findViewById(R.id.Btn_choice3);
tv2 = (TextView)findViewById(R.id.textView2);
score = (TextView)findViewById(R.id.textView_score);
try {
JSONArray jsonArray = new JSONArray(result);
JSONObject jsonData = jsonArray.getJSONObject(0);
question.setText(jsonData.getString("q_desc"));
fchoice.setText(jsonData.getString("fchoice"));
schoice.setText(jsonData.getString("schoice"));
tchoice.setText(jsonData.getString("tchoice"));
ans = jsonData.getString("q_ans");
tv2.setText(ans);
} catch(Exception e) {
Log.e("log_tag", e.toString());
}
}
}
}
three buttons are sharing same onClick in xml file by using
android:onClick="onClick"
the current problem i faced is that it always return "false" no matter i pressed which button. also, is there any way to store/pass "previous" async task data?
I have tried using internal storage but it doesnt work as well
EDIT:
my xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.95" >
<TextView
android:id="#+id/textView_score"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/player_score" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.95" >
<TextView
android:id="#+id/textView_question"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="#string/string_question"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="#+id/Btn_choice3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:text="#string/third_choice"
android:onClick="onClick" />
<Button
android:id="#+id/Btn_choice2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/Btn_submit"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:text="#string/second_choice"
android:onClick="onClick" />
<Button
android:id="#+id/Btn_choice1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/Btn_choice2"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:text="#string/first_choice"
android:onClick="onClick" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="TextView" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/textView1"
android:text="TextView" />
</RelativeLayout>
</LinearLayout
textview2 and textview3 are used to test my output and display them as text
try this if(inputtext.equals(tv2.getText().toString())) instead of if(inputtext == tv2.getText().toString())
becasue the == operator checks to see if the two strings are exactly the same object.
The .equals() method will check if the two strings have the same value.
i ma creating android application that get data from web using json and put the data in a listview then after the user click and select a specific data the system will display details in second activity that show the name and some details each value in a textview .
the problem is that after the user select from the list view the data displayed as a one block
can anyone help me to fix this error ??
this is the onListItemClick
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
try {
String item = (String)l.getItemAtPosition(position);
//PostalCodes.get(position);
/*
String PLACENAME = postalCode.get(PLACE_NAME_TAG).toString();
String LATITUDE = postalCode.get(LATITUDE_TAG).toString();
String LONGITUDE = postalCode.get(LONGITUDE_TAG).toString();
String POSTALCODE = postalCode.get(POSTAL_CODE_TAG).toString();
*/
Log.e("position of the Item in the list", "you select the item number " + PostalCodes.getString(position));
Intent in = new Intent(getBaseContext(), Row_Item.class);
in.putExtra("placename", item);
// in.putExtra("lat", LATITUDE);
// in.putExtra("lng", LONGITUDE);
// in.putExtra("postaCode", POSTALCODE);
startActivity(in);
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.e("Error in the onListItemClick",
"LOOK AT THE onListItemClick method");
}
}
the second activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_row__item);
Place_Name = (TextView)findViewById(R.id.textView1);
txtlat = (TextView)findViewById(R.id.textLAT);
txtlng = (TextView)findViewById(R.id.textLNG);
txtPostalCode = (TextView)findViewById(R.id.textPSTC);
Bundle b = getIntent().getExtras();
value1 = b.getString("placename");
// value2 = b.getString("lat");
// value3 = b.getString("lng");
// value4 = b.getString("postaCode");
Place_Name.setText(value1);
// txtlat.setText(value2);
// txtlng.setText(value3);
// txtPostalCode.setText(value4);
}
activity_row_item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".Row_Item" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="35dp"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:layout_marginTop="28dp"
android:text="LAT" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView2"
android:layout_marginTop="24dp"
android:text="LNG" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView3"
android:layout_marginTop="32dp"
android:text="POSTAL CODE" />
<TextView
android:id="#+id/textLAT"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView2"
android:layout_alignParentRight="true"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textLNG"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView3"
android:layout_alignParentRight="true"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textPSTC"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView4"
android:layout_alignParentRight="true"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
I would save the data in different TextViews. That seems to be the best way to get your data correctly.