I have 2 activities. The first one displays a list of data obtained from the MySQL table. By clicking on a list item, the next activity on which information about the pressed item will be displayed will be opened. But for this I need to create a new database query and get only the column that I passed as the "id" from listview
MainAcitvity
public class MainActivity extends AppCompatActivity {
ListView listView;
DataBase dataBase;
SQLiteDatabase sqLiteDatabase;
FloatingActionButton fabMain;
MySimpleAdapter simpleCursorAdapter;
Cursor cursor;
Task taskClass;
TextView tvTitleItemList, tvTextItemList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fabMain = findViewById(R.id.fab_main);
listView = findViewById(R.id.rv_list);
tvTitleItemList = findViewById(R.id.tv_title_item_list);
tvTextItemList = findViewById(R.id.tv_text_item_list);
dataBase = new DataBase(this);
sqLiteDatabase = dataBase.getWritableDatabase();
//next activity and add in database
fabMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
}
});
//get
cursor = sqLiteDatabase.query(dataBase.DATABASE_TABLE, null, null, null, null, null, null);
simpleCursorAdapter = new MySimpleAdapter(MainActivity.this, cursor, 0);
listView.setAdapter(simpleCursorAdapter);
//delete
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, TaskActivity.class );
String value = simpleCursorAdapter.id;
intent.putExtra("id", value);
startActivity(intent);
}
});
}
#Override
protected void onRestart() {
super.onRestart();
simpleCursorAdapter = new MySimpleAdapter(MainActivity.this, cursor, 0);
listView.setAdapter(simpleCursorAdapter);
}
activity in which you need to re-create a database query by id
public class TaskActivity extends AppCompatActivity {
TextView tvTitleActivityTask, tvTextActivityTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task);
tvTitleActivityTask = findViewById(R.id.tv_title_activity_task);
tvTextActivityTask = findViewById(R.id.tv_text_activity_task);
Intent intent = getIntent();
intent.getExtras();
String valueId = intent.getStringExtra("id");
}
}
Related
I am creating a simple tasklist app in Android Studios.
I have two activities as following (removed imports and package specifications):
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
EditText taskAdd;
Button add;
public ListView tasks;
public Integer pos = 0;
public ArrayList<String> taskArray;
public ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
taskAdd = findViewById(R.id.taskAdd);
add = findViewById(R.id.add);
tasks = findViewById(R.id.tasks);
taskArray = FileHelper.readData(this);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, taskArray);
tasks.setAdapter(adapter);
add.setOnClickListener(this);
tasks.setOnItemClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.add:
String entered = taskAdd.getText().toString();
if (entered != "" || entered != null || entered != "null") {
adapter.add(entered);
taskAdd.setText("");
FileHelper.writeData(taskArray, this);
Toast.makeText(this, "Task Added!", Toast.LENGTH_SHORT).show();
}
break;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
pos = position;
Intent intent = new Intent(MainActivity.this, Pop.class);
startActivity(intent);
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
processExtraData();
}
private void processExtraData(){
Bundle extras = getIntent().getExtras();
if (extras != null) {
int value = extras.getInt("Value");
if (value == 1) {
taskArray.remove(pos);
adapter.notifyDataSetChanged();
Toast.makeText(this, "Task Removed!", Toast.LENGTH_SHORT).show();
}
}
}
}
Pop.java (a popup)
public class Pop extends Activity implements View.OnClickListener {
Button deleteButton;
Button finishedButton;
Button timerButton;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.popwindow);
deleteButton = findViewById(R.id.deleteButton);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
getWindow().setLayout((int)(width*0.5),(int)(height*0.5));
deleteButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent i = new Intent(this, MainActivity.class);
i.putExtra("Value", 1);
startActivity(i);
}
}
After I click deleteButton in Pop.java, processExtraData in MainActivity.java is supposed to run. The Toast does appear, but the selected object in the ListView is not deleted. No errors are thrown either. In addition, using Log.d to check the size of taskArray confirmed that this is not just a graphical issue. Why is this the case, and how should I go about fixing it?
Thank you for replying in advance.
The issue is that you are using an object reference instead of a primitive data type, and so when you are calling taskArray.remove(pos), it is looking for pos the object rather than its denoted integer value.
Instead of:
taskArray.remove(pos);
try:
taskArray.remove(pos.intValue());
Excuse my noobness. I just don't understand how to implement it to work with my code. What I'm doing is editing a name that's in a list view. When editing the name in "EditDeleteList" and get back to the previous activity (ListView) to see the name updated within the list view, nothing happens. I have to go out of the activity completely to see the change reflected. How do I get this to update? I implement an onActivityReult() method but then get this error message "java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference" so I removed it completely. How I could get the list view to update without getting that error message?
ListView.Java
public class ListView extends AppCompatActivity {
private static final String TAG = "ListView";
DatabaseHelper mDatabaseHelper;
Button btnAdd;
private EditText editText;
private android.widget.ListView listView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
mDatabaseHelper = new DatabaseHelper(this);
btnAdd = (Button) findViewById(R.id.btnAdd);
editText = (EditText) findViewById(R.id.editText);
listView = (android.widget.ListView) findViewById(R.id.lv);
ArrayList<String> list = getIntent().getStringArrayListExtra("myList");
android.widget.ListView lv = (android.widget.ListView) findViewById(R.id.lv);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
//Takes user back to the main activity
ImageView ivBack = (ImageView) findViewById(R.id.ivBackArrow);
ivBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: pressed back arrow");
Intent intent = new Intent(ListView.this, MainActivity.class);
startActivity(intent);
}
});
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newEntry = editText.getText().toString();
if (editText.length() != 0) {
addData(newEntry);
editText.setText("");
} else {
toastMessage("you must put something in the text field");
}
}
});
populateListView();
}
public void addData(String newEntry) {
boolean insertData = mDatabaseHelper.addData(newEntry);
if (insertData) {
toastMessage("Successfully inserted");
recreate();
} else {
toastMessage("Whoops, something went wrong");
}
}
private void toastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
private void populateListView() {
Log.d(TAG, "populateListView: displaying data in the listview");
//get data and append to list
Cursor data = mDatabaseHelper.getData();
ArrayList<String> listData = new ArrayList<>();
while(data.moveToNext()) {
//get the value from the database in column 1
//set it to the arraylist
listData.add(data.getString(1));
}
//create arraylist and set it to the adapter
ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
listView.setAdapter(adapter);
//set onclick listen to edit activity
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
String name = adapterView.getItemAtPosition(position).toString();
Log.d(TAG, "onItemClick: you clicked on " + name);
Cursor data = mDatabaseHelper.getItemID(name); //get the id associated with that name
int itemID = -1;
while (data.moveToNext()) {
itemID = data.getInt(0);
}
if (itemID > -1) {
Log.d(TAG, "onItemID: the ID is: " + itemID);
Intent editScreenIntent = new Intent(ListView.this, EditDeleteList.class);
editScreenIntent.putExtra("id",itemID);
editScreenIntent.putExtra("name",name);
startActivity(editScreenIntent);
} else {
toastMessage("No ID found");
}
}
});
}
}
EditDeleteList.java
public class EditDeleteList extends AppCompatActivity {
private static final String TAG = "EditDeleteList";
DatabaseHelper mDatabaseHelper;
private ImageView ivDelete;
private ImageView ivApprove;
private EditText editHashtag;
private String selectedName;
private int selectedID;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_delete);
mDatabaseHelper = new DatabaseHelper(this);
editHashtag = (EditText) findViewById(R.id.editHashtag);
ivDelete = (ImageView) findViewById(R.id.ivDelete);
ivApprove = (ImageView) findViewById(R.id.ivApprove);
//get the intent extra from the ListView activity
final Intent receivedIntent = getIntent();
//get item ID passed as an extra
selectedID = receivedIntent.getIntExtra("id", -1);
//get name passed as an extra
selectedName = receivedIntent.getStringExtra("name");
//set text field to selected item text
editHashtag.setText(selectedName);
ivApprove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String item = editHashtag.getText().toString();
if (!item.equals(null)) {
mDatabaseHelper.updateName(item, selectedID, selectedName);
} else {
toastMessage("you must enter a #hashtag");
}
finish();
}
});
}
private void toastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
In the EditDeleteList.java I have an onClickListener that saves the changes and goes back to the previous activity by using finish();
ivApprove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String item = editHashtag.getText().toString();
if (!item.equals(null)) {
mDatabaseHelper.updateName(item, selectedID, selectedName);
} else {
toastMessage("you must enter a #hashtag");
}
finish();
}
});
Notify the adapter in some part of the activity lifecycle.
OnCreate() should not run when you go back (this is the reason you have to completely recreate the activity to see the list updated) so you should use OnRestart/OnStart/OnResume to notify the adapter to check for new items.
Check this image
I want to pass a string to another activity through click on the Listview, but it says I have something wrong.The purpose is to modify the data change when the user wants just to change some words and then update to the data.
Here is the data structure.
https://ppt.cc/f02tWx
It says : https://ppt.cc/f8ZYKx
This is the listview on click part
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
hom.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
adapter.getItem(position);
String title = dataSnapshot.child(String.valueOf(position)).getValue().toString();
Intent intent = new Intent(MeTodolist.this, MeTodolistModify.class);
Bundle bundle = new Bundle();
bundle.putString("title", title);
intent.putExtras(bundle);
startActivity(intent);
Log.e("CHANGE",title);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
This is the modifying page.
public class MeTodolistModify extends AppCompatActivity implements View.OnClickListener {
private String student_id,student_name,title;
private EditText addtext;
private Button sure;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_me_todolist_modify);
Intent intent = getIntent();
Bundle bundle = getIntent().getExtras();
String title = bundle.getString("title");
student_id = intent.getStringExtra("student_id");
student_name = intent.getStringExtra("student_name");
createDetail();
}
private void createDetail(){
final FirebaseDatabase db = FirebaseDatabase.getInstance();
final DatabaseReference ref = db.getReference("Student").child(student_id).child("event");
sure = findViewById(R.id.sure);
sure.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent;
switch (v.getId()) {
case R.id.sure:
intent = new Intent(MeTodolistModify.this, MeTodolist.class);
intent.putExtra("student_id", student_id );
intent.putExtra("student_name",student_name);
startActivity(intent);
break;
}
}
});
}
#Override
public void onClick(View v) {
}
}
You can achieve that by just few lines of code
Intent intent = new Intent(MeTodolist.this, MeTodolistModify.class);
String title = dataSnapshot.child(String.valueOf(position)).getValue().toString();
intent.putExtra("title", title);
startActivity(intent);
Log.e("CHANGE",title);
MeTodolistModify
String title = getIntent().getStringExtra("title");
Why are you passing Bundle with intent extra? just use one method.
Bundle bundle=new Bundle();
bundle.putString("title", title);
intent.putExtras(bundle);
startActivity(intent);
and from the receiver.
Intent intent = getIntent();
Bundle bundle = getIntent().getExtras();
if(bundle !=null)
String title = bundle.getString("title");
why you are receiving these student_id and student_name. you did not pass them.
student_id = intent.getStringExtra("student_id");
student_name = intent.getStringExtra("student_name");
This is my code:
public class MainActivity extends AppCompatActivity {
ListView listView ;
ArrayList<String> StoreContacts, id;
Bundle bundle;
ArrayAdapter<String> arrayAdapter ;
Cursor cursor;
Intent intent;
String name, phonenumber ;
public static final int RequestPermissionCode = 1 ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.listview1);
StoreContacts = new ArrayList<String>();
id = new ArrayList<String>();
EnableRuntimePermission();
GetContactsIntoArrayList();
arrayAdapter = new ArrayAdapter<String>(
MainActivity.this,
R.layout.contact_items_listview,
R.id.textView, StoreContacts
);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
bundle =new Bundle();
/*SharedPreferences.Editor editor=getSharedPreferences("Suyash",MODE_PRIVATE).edit();
editor.putString("ID",id.get(i));
editor.apply();*/
intent = new Intent(MainActivity.this, SingleContact.class);
bundle.putString("ID",id.get(i));
intent.putExtra("ID",id.get(i));
startActivity(intent);
}
});
}
public void GetContactsIntoArrayList(){
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null, null, null);
while (cursor.moveToNext()) {
id.add(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID)));;
name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
phonenumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
StoreContacts.add(name + " " + ":" + " " + phonenumber);
}
cursor.close();
}
public void EnableRuntimePermission(){
if (ActivityCompat.shouldShowRequestPermissionRationale(
MainActivity.this,
Manifest.permission.READ_CONTACTS))
{
Toast.makeText(MainActivity.this,"CONTACTS permission allows us to Access CONTACTS app", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(MainActivity.this,new String[]{
Manifest.permission.READ_CONTACTS}, RequestPermissionCode);
}
}
#Override
public void onRequestPermissionsResult(int RC, String per[], int[] PResult) {
switch (RC) {
case RequestPermissionCode:
if (PResult.length > 0 && PResult[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this,"Permission Granted, Now your application can access CONTACTS.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this,"Permission Canceled, Now your application cannot access CONTACTS.", Toast.LENGTH_LONG).show();
}
break;
}
}
}
on receiving end:
public class SingleContact extends AppCompatActivity {
Bundle bundle=getIntent().getExtras();
//SharedPreferences preferences=getSharedPreferences("Suyash",MODE_PRIVATE);
0String string = bundle.getString("ID",null);
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_contact);
button= (Button) findViewById(R.id.button);
//string= bundle.getString("ID");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(SingleContact.this, string, Toast.LENGTH_SHORT).show();
}
});
}
}
the crashes when I click the item.
i have tried sharedpreference too, it does the same thing. im using android studio 2.3.3.
anyone suggest what i should do.
please help
You can not get the bundle before onCreate(). Write your code something like below and it will resolve your error.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_contact);
// Your bundle code.
Bundle bundle=getIntent().getExtras();
String string = bundle.getString("ID",null);
}
Probably wrong initialization of bundle data in SingleContact Activity, you should initialise inside of onCreate method
public class SingleContact extends AppCompatActivity {
Bundle bundle;
String string;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_contact);
bundle = getIntent().getExtras()
button= (Button) findViewById(R.id.button);
string= bundle.getString("ID");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(SingleContact.this, string, Toast.LENGTH_SHORT).show();
}
});
}
}
I'm trying to put onListItemClick, but when I start my app nothing happens with onListItemClick. Can anyone help me with this?
Here is my code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
db = (new DatabaseHelper(this)).getWritableDatabase();
searchText = (EditText) findViewById(R.id.searchText);
employeeList = (ListView) findViewById(R.id.list);
Button searchButton = (Button) findViewById(R.id.searchButton);
searchButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
search(employeeList);
}
});
}
public void search(View view) {
// || is the concatenation operation in SQLite
cursor = db
.rawQuery(
"SELECT _id, firstName, lastName, title FROM employee WHERE firstName || ' ' || lastName LIKE ?",
new String[] { "%" + searchText.getText().toString()
+ "%" });
adapter = new SimpleCursorAdapter(this, R.layout.employee_list_item,
cursor, new String[] { "firstName", "lastName", "title" },
new int[] { R.id.firstName, R.id.lastName, R.id.title });
employeeList.setAdapter(adapter);
}
public void onListItemClick(ListView parent, View view, int position, long id) {
Intent intent = new Intent(this, EmployeeDetails.class);
Cursor cursor = (Cursor) adapter.getItem(position);
intent.putExtra("EMPLOYEE_ID", cursor.getInt(cursor.getColumnIndex("_id")));
startActivity(intent);
}
}
There is no error messages and search is working normally.
employeeList = (ListView) findViewById(R.id.list);
add these line below the above line
employeeList = (ListView) findViewById(R.id.list);
employeeList .setOnItemClickListener(this);
Updated:: sample code
public class SampleActivity extends Activity implements OnItemClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(mWebView);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
// TODO Auto-generated method stub
}
}
register an OnItemClickListener() with setOnItemClickListener for your listview like this
listView.setOnItemClickListener(new OnItemClickListener() {
#Override public void onItemClick(AdapterView<?> adapter, View view, int pos, long id) {
Intent intent = new Intent(this, EmployeeDetails.class);
Cursor cursor = (Cursor) adapter.getItem(pos);
intent.putExtra("EMPLOYEE_ID", cursor.getInt(cursor.getColumnIndex("_id")));
startActivity(intent);
}
});
You have to register your listener as listview.setOnItemClickListener(this) in your code.
Try this
listview.setOnItemClickListener(new OnItemClickListener() {
// Your Code Goes Here
});