Error making a cancel button. Can someone help me? - java

I am making a simple application, you put your name, click in a button, select a hobby and then it returns to the main layout your name and hobby together. I am having a problem when i click in the "Cancelar (Cancel)" button the application keeps getting a fatal error. What do you thing it could be?
MainActivity:
package com.example.holaamigos;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
public final static String EXTRA_SALUDO = "com.example.holaamigos.SALUDO";
TextView txtfinal;
String saludo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText txtNombre = (EditText)findViewById(R.id.TxtNombre);
final Button btnHola = (Button)findViewById(R.id.BtnHola);
final CheckBox checkbox1 =(CheckBox)findViewById(R.id.checkBox1);
txtfinal=(TextView)findViewById(R.id.textView1);
checkbox1.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton arg0,
boolean checked) {
if (checked)
{
Toast.makeText(checkbox1.getContext(), "Activo", Toast.LENGTH_LONG).show();
btnHola.setVisibility(0);
btnHola.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ActivitySaludo.class);
saludo = txtNombre.getText().toString();
intent.putExtra(EXTRA_SALUDO, saludo);
startActivityForResult(intent, 1);
}
});
}
else
{
Toast.makeText(checkbox1.getContext(), "Inactivo", Toast.LENGTH_SHORT).show();
btnHola.setVisibility(View.INVISIBLE);
}
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK);
String string= data.getStringExtra("HOBBY");
txtfinal.setText("Nombre:" + saludo + " " + "Hobby:" + string);
if (resultCode == RESULT_CANCELED){
}
}
#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;
}
}
ActivitySaludo:
package com.example.holaamigos;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
public class ActivitySaludo extends Activity {
String myspinner;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saludo);
Intent intent = getIntent();
String saludo = intent.getStringExtra(MainActivity.EXTRA_SALUDO);
TextView txtCambiado = (TextView) findViewById(R.id.TxtSaludo);
txtCambiado.setText(getString(R.string.hola_saludo) + " " + saludo);
final Spinner spinner = (Spinner)findViewById(R.id.SpinnerSaludo);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.hobby, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener () {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
parent.getItemAtPosition(pos);
myspinner = spinner.getItemAtPosition(pos).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
//another call
}
});
final Button BtnAceptar=(Button) findViewById(R.id.buttonAceptar);
BtnAceptar.setOnClickListener(new OnClickListener (){
#Override
public void onClick(View v) {
Intent iboton = new Intent();
iboton.putExtra("HOBBY", myspinner);
setResult(RESULT_OK, iboton);
finish();
}
});
final Button BtnCancelar=(Button) findViewById(R.id.buttonCancelar);
BtnCancelar.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Intent iboton2 = new Intent();
iboton2 = null;
setResult(RESULT_CANCELED, iboton2);
finish();
}
});
}
}

if (resultCode == RESULT_OK);
String string= data.getStringExtra("HOBBY");
txtfinal.setText("Nombre:" + saludo + " " + "Hobby:" + string);
this is where the error is.. you need to remove the ; from the end of if statement and put { there and similarly end the block with }

Related

Recycler view does not show up

I am having problem with my recyclerview I builed an app in android studio which suppose to create contacts and watch their cards using cardview and recyclerview the issue is that the list of contacts is not shown instead I am seeing a white screen
so here is my code:
import android.net.sip.SipSession;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
/*Connect contact list to
*
* */
public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ContactViewHolder> {
private List<Contact> contacts;
public ContactAdapter(List<Contact> contacts) {
this.contacts = contacts;
}
interface ContactsListener{
void onContactClicked(int position,View view);
}
ContactsListener listener;
public void setListener(ContactsListener listener){
this.listener=listener;
}
public class ContactViewHolder extends RecyclerView.ViewHolder {
ImageView contactpicture;
TextView contactname;
TextView contactphone;
TextView contactemail;
public ContactViewHolder(View itemview) {
super(itemview);
contactpicture = itemview.findViewById(R.id.card_image);
contactphone = itemview.findViewById(R.id.contact_email);
contactphone = itemview.findViewById(R.id.contact_phone);
contactname = itemview.findViewById(R.id.contact_name);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null)
listener.onContactClicked(getAdapterPosition(), view);
}
});
}
}
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup parent,int viewType){
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.contact_layout,parent,false);
ContactViewHolder holder=new ContactViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(ContactViewHolder holder,int position){
Contact contact=contacts.get(position);
holder.contactpicture.setImageBitmap(contact.getPhoto());
holder.contactname.setText(contact.getName());
holder.contactphone.setText(contact.getPhone());
holder.contactemail.setText(contact.getEmail());
}
#Override
public int getItemCount(){
return contacts.size();
}
}
package com.example.b_safe;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
/*Define the list of contacts*/
public class ContactsList extends Activity {
#Override
protected void onCreate(#Nullable Bundle saveInstanceState){
super.onCreate(saveInstanceState);
setContentView(R.layout.show_contacts_activity);//לבדוק שזה מתקיים
RecyclerView recyclerview=findViewById(R.id.contacts_list);
recyclerview.setHasFixedSize(true);
recyclerview.setLayoutManager(new LinearLayoutManager( this));//צריך להוסיף this
ContactManager manager=ContactManager.getInstance(this);
ContactAdapter adapter=new ContactAdapter(manager.getContacts());
recyclerview.setAdapter(adapter);
adapter.setListener(new ContactAdapter.ContactsListener() {
#Override
public void onContactClicked(int position, View view) {
}
});
}
}
package com.example.b_safe;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
/*Adds new member to the contacts list
*
*
* */
public class AddContactActivity extends AppCompatActivity{
Bitmap bitmap;
EditText nameEt,phone_numberEt,emailEt;
ImageView img;
final int CAMERA_REQUEST=1;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_contact_activity);
nameEt=findViewById(R.id.name_input);
phone_numberEt=findViewById(R.id.phone_input);
emailEt=findViewById(R.id.email_input);
img=findViewById(R.id.photo_result);
Button takepicture=findViewById(R.id.take_pic);
takepicture.setOnClickListener(new View.OnClickListener() {//Activation
#Override
public void onClick(View v) {
Intent camera=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camera,CAMERA_REQUEST);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==CAMERA_REQUEST&&resultCode==RESULT_OK){ //checks if results where properly
bitmap=(Bitmap)data.getExtras().get("data");
img.setImageBitmap(bitmap);//saving as contact's photo
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {//Load menu type
getMenuInflater().inflate(R.menu.contact_menu,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {//fulfill actions
switch(item.getItemId()){
case R.id.action_save:
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("Please confirm")
.setMessage("Would you like to save the following contact?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Contact contact=new Contact(nameEt.getText().toString(),phone_numberEt.getText().toString(),emailEt.getText().toString(),bitmap);
ContactManager manager=ContactManager.getInstance(AddContactActivity.this);
manager.addContact(contact);//Manager saved data
//Data zeroing
nameEt.setText("");
phone_numberEt.setText("");
emailEt.setText("");
img.setImageBitmap(null);
}})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(AddContactActivity.this,"The conatct saved",Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(AddContactActivity.this,"The conatct saved",Toast.LENGTH_SHORT).show();
}
}).show();
break;
case R.id.action_back:
finish();
}
return super.onOptionsItemSelected(item);//Loads activity
}
}
AdapterActivity is the subclass adapter AddContactActivity creates new contacts and the problem is with the ContactsList activity which holds the list and does not show up

how to check radio buttons programatically when the scanned qr match with text in the listview

I am developing attendance system and i have a listview with students name i want to programatically check or uncheck the radio buttons in the listview when the scanned qr matchs the student name I tried to do it in the ontextchengeListner method of txtresult but the text is changing many time even in reading a single qr
This are my java classes
CustomAdapter.java
package com.attendance.olana.qr_scanner;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by olana on 23/03/2018.
*/
public class CustomAdapter extends BaseAdapter {
Context context;
String[] questionsList;
public static String message;
LayoutInflater inflter;
public static TextView question ;
public static RadioButton yes,no ;
public static ArrayList<String> selectedAnswers;
public CustomAdapter(Context applicationContext, String[] questionsList) {
this.context = context;
this.questionsList = questionsList;
// initialize arraylist and add static string for all the questions
selectedAnswers = new ArrayList<>();
for (int i = 0; i < questionsList.length; i++) {
selectedAnswers.add("Not Attempted");
}
inflter = (LayoutInflater.from(applicationContext));
}
#Override
public int getCount() {
return questionsList.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.main, null);
// get the reference of TextView and Button's
question = (TextView) view.findViewById(R.id.question);
yes = (RadioButton) view.findViewById(R.id.yes);
no = (RadioButton) view.findViewById(R.id.no);
// perform setOnCheckedChangeListener event on yes button
yes.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// set Yes values in ArrayList if RadioButton is checked
if (isChecked)
selectedAnswers.set(i, "Present");
}
});
// perform setOnCheckedChangeListener event on no button
no.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// set No values in ArrayList if RadioButton is checked
if (isChecked)
selectedAnswers.set(i, "Absent");
}
});
// set the value in TextView
question.setText(questionsList[i]);
return view;
}
}
list.java
package com.attendance.olana.qr_scanner;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.Toast;
/**
* Created by olana on 23/03/2018.
*/
public class list extends AppCompatActivity {
ListView simpleList;
public static String[] questions;
Button submit,scan;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
scan =(Button)findViewById(R.id.scan);
// get the string array from string.xml file
questions = getResources().getStringArray(R.array.student);
// get the reference of ListView and Button
simpleList = (ListView) findViewById(R.id.simpleListView);
submit = (Button) findViewById(R.id.submit);
// set the adapter to fill the data in the ListView
CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), questions);
simpleList.setAdapter(customAdapter);
scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i;
i = new Intent(list.this,MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
}
});
// perform setOnClickListerner event on Button
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String message = "";
// get the value of selected answers from custom adapter
for (int i = 0; i < CustomAdapter.selectedAnswers.size(); i++) {
message = message + "\n" + (i + 1) + " " + CustomAdapter.selectedAnswers.get(i);
}
// display the message on screen with the help of Toast.
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
});
}
}
MainActivity.java
package com.attendance.olana.qr_scanner;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Vibrator;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.SparseArray;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.barcode.Barcode;
import com.google.android.gms.vision.barcode.BarcodeDetector;
import java.io.IOException;
import java.util.jar.Manifest;
public class MainActivity extends AppCompatActivity {
BarcodeDetector barcodeDetector;
SurfaceView camerapreview;
CameraSource cameraSource;
TextView txtresult;
String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button finish = (Button) findViewById(R.id.finish);
//Button scan = (Button) findViewById(R.id.scan);
finish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
});
camerapreview = (SurfaceView) findViewById(R.id.camerapreview);
txtresult = (TextView) findViewById(R.id.txtresult);
barcodeDetector = new BarcodeDetector.Builder(this)
.setBarcodeFormats(Barcode.QR_CODE)
.build();
cameraSource = new CameraSource
.Builder(this, barcodeDetector)
.setRequestedPreviewSize(640, 480)
.build();
//add event
camerapreview.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
cameraSource.start(camerapreview.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
try {
cameraSource.start(camerapreview.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> qrcodes = detections.getDetectedItems();
if (qrcodes.size() != 0) {
txtresult.post(new Runnable() {
#Override
public void run() {
//create vibration
Vibrator vibrator = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(100);
txtresult.setText(qrcodes.valueAt(0).displayValue);
//barcodeDetector.release();
}
});
}
}
});
}
}
Please tell me where i can implement these the programatically checking or unchecking the radio button when the name in the listview matchs the scanned qr please help me

Cannot Resolve OnClickListener

I am a highschool student in an Android App Development class. I was making an introduction slider for my app with buttons to go to the next activity. I unfortunately get the error cannot resolve symbol 'OnClickListener'. I made sure that this was all written under the OnCreate(); method and included the import statement for the OnClickListener(); but it still cannot resolve the symbol. Is there another import statement or was this misplaced? Below you will find my code.
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.view.View.OnClickListener;
public class SecondActivity extends AppCompatActivity {
private ViewPagerAdapter viewPagerAdapter;
private ViewPager viewPager;
private IntroManager introManager;
private TextView [] dots;
private LinearLayout dotsLayout;
private int[] layouts;
Button next,skip;
View view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
introManager = new IntroManager(this);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.second_activity);
if(!introManager.Check())
{
introManager.setFirst(false);
Intent intent = new Intent(SecondActivity.this,ThirdActivity.class);
startActivity(intent);
finish();
}
layouts= new int[]{R.layout.second_activity,R.layout.third_activity,R.layout.fourth_activity,R.layout.fifth_activity};
if(Build.VERSION.SDK_INT>=21){
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE|View.SYSTEM_UI_FLAG_FULLSCREEN);
}
viewPager = (ViewPager) findViewById(R.id.view_pager);
dotsLayout= (LinearLayout) findViewById(R.id.layoutdots);
skip = (Button) findViewById(R.id.btn_skip);
next = (Button) findViewById(R.id.btn_next);
addBottomDots(0);
viewPagerAdapter= new ViewPagerAdapter();
viewPager.setAdapter(viewPagerAdapter);
viewPager.addOnPageChangeListener(viewListener);
skip.setOnClickListener(new view.OnClickListener(){
#Override
public void onClick(View view){
Intent intent = new Intent(SecondActivity.this,FifthActivity.class);
startActivity(intent);
finish();
}
});
next.setOnClickListener(new view.OnClickListener(){
#Override
public void onClick(View view){
int current = getItem(+1);
if(current<layouts.length){
viewPager.setCurrentItem(current);
}
else
{
Intent intent = new Intent(SecondActivity.this,ThirdActivity.class);
startActivity(intent);
finish();
}
}
});
}
private void addBottomDots(int position){
dots = new TextView[layouts.length];
int [] colorActive = getResources().getIntArray(R.array.dot_active);
int [] colorInactive = getResources().getIntArray(R.array.dot_inactive);
dotsLayout.removeAllViews();
for (int i = 0; i<dots.length; i++){
dots[i]= new TextView(this);
dots[i].setText(Html.fromHtml("&#8226;"));
dots[i].setTextSize(35);
dots[i].setTextColor(colorInactive[position]);
dotsLayout.addView(dots[i]);
}
if(dots[position].length()>0){
dots[position].setTextColor(colorActive[position]);
}
}
private int getItem(int i){
return viewPager.getCurrentItem() + 1;
}
ViewPager.OnPageChangeListener viewListener = new ViewPager.OnPageChangeListener(){
#Override
public void onPageScrolled(int position, float positionOffeet, int positionOffeetPixels){
}
#Override
public void onPageSelected(int position)
{
addBottomDots(position);
if (position==layouts.length-1){
next.setText("PROCEED");
skip.setVisibility(View.GONE);
}else{
next.setText("NEXT");
skip.setVisibility(View.VISIBLE);
}
}
#Override
public void onPageScrollStateChanged(int state)
{}
}
;
public void changetatusColor(){
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP){
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
}
}
public class ViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
#Override
public Object instantiateItem(ViewGroup container, int position){
layoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = LayoutInflater.inflate(layouts[position],container,false);
container.addView(v);
return v;
}
#Override
public int getCount(){
return 0;
}
#Override
public boolean isViewFromObject(View view,Object object){
return view==object;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object){
View v = (View) object;
container.removeView(v);
}
}
}
Do only one of those:
import android.view.View;
// note that View is uppercase
.setOnClickListener(new View.OnClickListener() {
import android.view.View.OnClickListener;
.setOnClickListener(new OnClickListener() {

Add item to listview from another activity (it only adds one item)

I have a problem in my code. I want to add items to a listview from another acivity onclickButton, but it only adds one item. And if I reapeat it, it only replaces the last added item. I can't figure out whats the problem some help please.
my code :
MainActivity:
package com.example.nasreddine.mtodubled; // project package
import android.app.AlertDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity; //imports statements
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import android.content.DialogInterface;
public class MainActivity extends AppCompatActivity {
AlertDialog.Builder alert;
public ArrayList<City> listItems;
ArrayAdapter adapter;
ListView cityListView;
#Override
protected void onCreate(Bundle savedInstanceState) { //onCreate State
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listItems=new ArrayList<>();
adapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,listItems);
//Displaying Data on ListView
cityListView=(ListView)findViewById(R.id.cityListView);
cityListView.setAdapter(adapter);
registerForContextMenu(cityListView);
listItems.add(new City("a","b","","","","",""));
listItems.add(new City("v","c","","","","",""));
updateListView();
cityListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
cityListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle("Delete Item from list");
alert.setMessage("Are you sure you want to delete?");
alert.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
listItems.remove(position);
adapter.notifyDataSetChanged();
}
});
alert.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alert.show();
return true;
}
});
}
public void updateListView() {
Bundle bundle = getIntent().getExtras();
Intent intent=getIntent();
if (bundle != null) {
City a=new City(intent.getStringExtra("city"),intent.getStringExtra("country"),"/","/","/","/","/");
//listItems.add(a);
adapter.add(a);
adapter.notifyDataSetChanged();
}
}
public boolean onOptionsItemSelected(MenuItem item){
if (item.getItemId()==R.id.action_add){
Intent intent=new Intent(MainActivity.this,AddCity.class);
startActivity(intent);
return (true);
}
return (super.onOptionsItemSelected(item));
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main,menu);
return super.onCreateOptionsMenu(menu);
}
}
AddCity.java
package com.example.nasreddine.mtodubled;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class AddCity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_city);
Button addButton=(Button)findViewById(R.id.addButton);
final TextView cityAddText=(TextView)findViewById(R.id.cityAddText);
final TextView countryAddText=(TextView)findViewById(R.id.countryAddText);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String city= cityAddText.getText().toString();
String country=countryAddText.getText().toString();
Intent intent =new Intent(AddCity.this,MainActivity.class);
intent.putExtra("city",city);
intent.putExtra("country",country);
startActivity(intent);
}
});
}
}
In your MainActivity.class start the AddCity.class using startActivityForResult().
public boolean onOptionsItemSelected(MenuItem item){
if (item.getItemId()==R.id.action_add){
Intent intent=new Intent(MainActivity.this,AddCity.class);
startActivityForResult(intent, requestCode); //ex: requestCode = 1
return (true);
}
return (super.onOptionsItemSelected(item));
}
After that in AddCity change add button click listener code with below:
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String city= cityAddText.getText().toString();
String country=countryAddText.getText().toString();
Intent intent =new Intent();
intent.putExtra("city",city);
intent.putExtra("country",country);
setResult(RESULT_OK, intent);
finish();
}
});
After that in MainActivity's onActivityResult() get data and add it to list. Also remove updatListView() method from MainActivity.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
getActivity().invalidateOptionsMenu();
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
City a=new City(data.getStringExtra("city"),data.getStringExtra("country"),"/","/","/","/","/");
listItems.add(a);
adapter.add(a);
adapter.notifyDataSetChanged();
}
}
}
}
You are restarting the MainActivity from AddCity Activity.
Rather than doing this, you need to start AddCity Activity, using method startActivityForResult().
And in AddCity Activity, rather than starting new MainActivity, you need to use setResult() method to send data to previous activity.
Also you need to override the onActivityResult method in MainActivity Class to owner the response from AddCity Activity.
Cheers!!!
Here is the code:
Class Main Activity,
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity
{
AlertDialog.Builder alert;
public List<City> listItems;
ArrayAdapter<City> adapter;
ListView cityListView;
#Override
protected void onCreate(Bundle savedInstanceState)
{ //onCreate State
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listItems = new ArrayList<>();
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listItems);
//Displaying Data on ListView
Button addButton = (Button) findViewById(R.id.addButton);
addButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
startActivityForResult(new Intent(MainActivity.this, AddCity.class), 1);
}
});
cityListView = (ListView) findViewById(R.id.cityListView);
cityListView.setAdapter(adapter);
registerForContextMenu(cityListView);
listItems.add(new City("a", "b"));
listItems.add(new City("v", "c"));
updateListView();
}
public void updateListView()
{
Bundle bundle = getIntent().getExtras();
Intent intent = getIntent();
if(bundle != null)
{
City a = new City(intent.getStringExtra("city"), intent.getStringExtra("country"));
//listItems.add(a);
adapter.add(a);
adapter.notifyDataSetChanged();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
if(requestCode == 1 && resultCode == RESULT_OK)
{
City a = new City(intent.getStringExtra("city"), intent.getStringExtra("country"));
//listItems.add(a);
adapter.add(a);
adapter.notifyDataSetChanged();
}
}
}
Class Add City,
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class AddCity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_city);
Button addButton = (Button) findViewById(R.id.addButton);
final TextView cityAddText = (TextView) findViewById(R.id.cityAddText);
final TextView countryAddText = (TextView) findViewById(R.id.countryAddText);
addButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
String city = cityAddText.getText().toString();
String country = countryAddText.getText().toString();
Intent intent = new Intent();
intent.putExtra("city", city);
intent.putExtra("country", country);
setResult(RESULT_OK, intent);
}
});
}
}
Hopefully, this will help you.
Cheers!!!

How to display all data from sqlite database

I'm making an app that will let users add their school subjects.
Before i continue let me give you my code:
MainActivity:
package cannon.gaming.mymarks;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends ActionBarActivity {
TextView textSubject;
String SUBJECT, PASS;
Context ctx = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
/*Button buttonAdd = (Button) findViewById(R.id.buttonAdd);
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), RegisterActivity.class);
intent.setFlags(intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivityForResult(intent, 0);
}
});*/
Button buttonAdd = (Button) findViewById(R.id.buttonAdd);
textSubject = (TextView) findViewById(R.id.textSubject);
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showInputDialog();
}
});
}
protected void showInputDialog() {
// get prompts.xml view
LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this);
View promptView = layoutInflater.inflate(R.layout.activity_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogBuilder.setView(promptView);
final EditText editText = (EditText) promptView.findViewById(R.id.edittext);
// setup a dialog window
alertDialogBuilder.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
SUBJECT = editText.getText().toString();
PASS = "0";
DatabaseOperations DB = new DatabaseOperations(ctx);
DB.putInformation(DB, SUBJECT, PASS);
Toast.makeText(getBaseContext(), "Subject added", Toast.LENGTH_SHORT).show();
finish();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create an alert dialog
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
TableData:
package cannon.gaming.mymarks;
import android.provider.BaseColumns;
/**
* Created by Asuspc on 01/07/2015.
*/
public class TableData {
public TableData()
{
}
public static abstract class TableInfo implements BaseColumns
{
public static final String USER_NAME = "user_name";
public static final String USER_PASS = "user_pass";
public static final String DATABASE_NAME = "user_info";
public static final String TABLE_NAME = "reg_info";
}
}
DatabaseOperations:
package cannon.gaming.mymarks;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* Created by Asuspc on 01/07/2015.
*/
public class DatabaseOperations extends SQLiteOpenHelper {
public static final int database_version = 1;
public String CREATE_QUERY = "CREATE TABLE "+ TableData.TableInfo.TABLE_NAME+"("+ TableData.TableInfo.USER_NAME+" TEXT,"+ TableData.TableInfo.USER_PASS+" TEXT);";
public DatabaseOperations(Context context) {
super(context, TableData.TableInfo.DATABASE_NAME, null, database_version);
Log.d("Database Operations", "Database created");
}
#Override
public void onCreate(SQLiteDatabase sdb)
{
sdb.execSQL(CREATE_QUERY);
Log.d("Database Operations", "Table created");
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2)
{
}
public void putInformation(DatabaseOperations dop,String name, String pass)
{
SQLiteDatabase SQ = dop.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(TableData.TableInfo.USER_NAME, name);
cv.put(TableData.TableInfo.USER_PASS, pass);
long k = SQ.insert(TableData.TableInfo.TABLE_NAME, null, cv);
Log.d("Database Operations", "One row inserted");
}
public Cursor getInformation(DatabaseOperations dop)
{
SQLiteDatabase SQ = dop.getReadableDatabase();
String[] columns = {TableData.TableInfo.USER_NAME, TableData.TableInfo.USER_PASS};
Cursor CR = SQ.query(TableData.TableInfo.TABLE_NAME, columns, null, null, null, null, null);
return CR;
}
}
Now let me explain.
When I press the "buttonAdd" button it will let me enter the subject name obviously, and save it in database.
But what I can't make is, I want to display all database on MainActivity.
And it should be like this:
names of subjects on the left side,
average of those subjects on the right side (the string PASS should be that average, that's why it is 0 when you first add the subject).
And I want to make each of those subjects clickable, so when you click it it should show you all marks from that subject and let you add or remove them.
Now, I guess, displaying data shouldn't be so hard, but still I need your help.
But making each subject clickable I really have no idea how.
And each subject having its own marks, I don't know, does it mean new activity for every new subject or new database or what?
EDIT:
MainActivity now:
package cannon.gaming.mymarks;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Build;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends ActionBarActivity {
String SUBJECT, PASS;
Context CTX = this;
private SimpleCursorAdapter adapter;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
/*Button buttonAdd = (Button) findViewById(R.id.buttonAdd);
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), RegisterActivity.class);
intent.setFlags(intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivityForResult(intent, 0);
}
});*/
Button buttonAdd = (Button) findViewById(R.id.buttonAdd);
displayListView();
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showInputDialog();
}
});
}
protected void showInputDialog() {
// get prompts.xml view
LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this);
View promptView = layoutInflater.inflate(R.layout.activity_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogBuilder.setView(promptView);
final EditText editText = (EditText) promptView.findViewById(R.id.edittext);
// setup a dialog window
alertDialogBuilder.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
SUBJECT = editText.getText().toString();
PASS = "0";
DatabaseOperations DB = new DatabaseOperations(CTX);
DB.putInformation(DB, SUBJECT, PASS);
Toast.makeText(getBaseContext(), "Subject added", Toast.LENGTH_SHORT).show();
adapter.notifyDataSetChanged();
displayListView();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create an alert dialog
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void displayListView()
{
DatabaseOperations DOP = new DatabaseOperations(CTX);
Cursor CR = DOP.getInformation(DOP);
CR.moveToFirst();
// The desired columns to be bound
String[] columns = new String[]{
TableData.TableInfo.USER_NAME,
TableData.TableInfo.USER_PASS
};
// the XML defined views which the data will be bound to
int[] to = new int[]{
R.id.code,
R.id.name,
};
adapter = new SimpleCursorAdapter(
this, R.layout.activity_login,
CR,
columns,
to,
0);
ListView listView = (ListView) findViewById(R.id.listView);
// Assign adapter to ListView
listView.setAdapter(adapter);
}
}
To display data, you should use ListView and CursorAdapter.
Here is sample code for you: http://www.mysamplecode.com/2012/07/android-listview-cursoradapter-sqlite.html
In that sample code, you can see:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the state's capital from this row in the database.
String countryCode =
cursor.getString(cursor.getColumnIndexOrThrow("code"));
Toast.makeText(getApplicationContext(),
countryCode, Toast.LENGTH_SHORT).show();
}
});
OnItemClickListener will help you to handle when a item in the listview is clicked.
Hope this will help you.

Categories

Resources