android arrayadapter declaration Error - java

When i declare the array adapter up as golbal public the app crash when i just start it
but when i declare it inside the onClick method it works fine
i need to know that happen ?
package com.rafahya.myapplication;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
public ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(MainActivity.this , android.R.layout.simple_list_item_1 ,arrayList);
public ArrayList<String> arrayList = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
arrayList.add("momen");
arrayList.add("ahmed");
arrayList.add("Amin");
Button button = (Button)findViewById(R.id.ok);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder momen = new AlertDialog.Builder(MainActivity.this)
.setTitle("Enter the Zip Code")
.setAdapter(arrayAdapter , new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this , "Momen" ,Toast.LENGTH_LONG).show();
}
});
momen.show();
}
});
}
}

public ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(MainActivity.this , android.R.layout.simple_list_item_1 ,arrayList);
With this line you are trying to access MainActivity before it is initialised. When you type this in the onClick it will be executed when you are inside onCreate and the class is already initialised.
As to how to fix it- First declare the variable
public ArrayAdapter<String> arrayAdapter;
and then inside the onCreate
arrayAdapter = new ArrayAdapter<String>(MainActivity.this , android.R.layout.simple_list_item_1 ,arrayList);

Related

How to remove everything from ListView using a button onClick?

How to remove everything from ListView using a button onClick? When i try "fullCourseList.clear();", I can't add any more courses and the page is refreshed only after visiting the page again
import static com.example.diplom.MainActivity.fullCourseList;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.example.diplom.model.Course;
import com.example.diplom.model.Order;
import java.util.ArrayList;
import java.util.List;
public class OrderPage extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_page);
ListView orders_list = findViewById(R.id.orders_list);
List<String> coursesTitle = new ArrayList<>();
for (Course c : MainActivity.fullCourseList) {
if(Order.items_id.contains(c.getId()))
coursesTitle.add(c.getTitle());
}
orders_list.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, coursesTitle));
}
public void openMain(View view){
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
public void onClick(View v) {
//fullCourseList.clear();
}
}
You should save off the adapter so you can call clear() on it. Clearing the list this way will also automatically notify the adapter to update. Since you copied your data into a new list (coursesTitle) clearing the original list will have no immediate effect.
For example:
public class OrderPage extends AppCompatActivity {
private ListView orders_list;
private ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_page);
orders_list = findViewById(R.id.orders_list);
List<String> coursesTitle = new ArrayList<>();
for (Course c : MainActivity.fullCourseList) {
if(Order.items_id.contains(c.getId()))
coursesTitle.add(c.getTitle());
}
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, coursesTitle)
orders_list.setAdapter(adapter);
}
public void onClick(View v) {
adapter.clear();
}
}
Edit
If you also want to clear the currently displayed course items out of the master list, you would need to add code like this as well. If that isn't want you want, you need to be more clear in your question about the desired behavior.
public void onClick(View v) {
// clear what is currently shown in the list
adapter.clear();
// Clear the currently displayed entries out of the master list.
// You may also be able to use "removeIf" if you have a new
// enough java/api version
Iterator<Course> itr = MainActivity.fullCourseList.iterator();
while (itr.hasNext()) {
Course c = itr.next();
if(Order.items_id.contains(c.getId())) {
itr.remove();
}
}
// And if you want to ENTIRELY clear the master list, you
// could just do this instead
// MainActivity.fullCourseList.clear()
}
Everything was easier than I thought, I confused myself with my own class names. Thank you all very much for your help!
This worked:
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;;
import android.widget.ListView;
import com.example.diplom.model.Course;
import com.example.diplom.model.Order;
import java.util.ArrayList;
import java.util.List;
public class OrderPage extends AppCompatActivity {
private ListView orders_list;
private ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_page);
orders_list = findViewById(R.id.orders_list);
List<String> coursesTitle = new ArrayList<>();
for (Course c : MainActivity.fullCourseList) {
if(Order.items_id.contains(c.getId()))
coursesTitle.add(c.getTitle());
}
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, coursesTitle);
orders_list.setAdapter(adapter);
}
public void onClick(View v) {
adapter.clear();
Order.items_id.clear();
}
public void openMain(View view){
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
}
After clearing the ArrayList you have to notify the adapter that the data source has been changed.
public class OrderPage extends AppCompatActivity {
private ListView orders_list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_page);
orders_list = findViewById(R.id.orders_list);
List<String> coursesTitle = new ArrayList<>();
for (Course c : MainActivity.fullCourseList) {
if(Order.items_id.contains(c.getId()))
coursesTitle.add(c.getTitle());
}
orders_list.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, coursesTitle));
}
public void openMain(View view){
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
public void onClick(View v) {
fullCourseList.clear();
orders_list.getAdapter().notifyDataSetChanged();
}
}

how to fix my intent when i put the parameters

i get some problem when i use the intent, he said "cannot resolve constructor Intent('....')" , i dont know what is wrong in my code but you can see what i m importing here
package com.example.noen.myintentapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = findViewById(R.id.btn_move);
btn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.btn_move:
Intent intn = new Intent(MainActivity.this,target1.class);
break;
}
}
}

Clicked list item into a String and transported to another activity

I have made this app where in one particular activity i have a all the items listed in a list view. when you click the list item it goes to another activity where similar thing is happening. after that i was the clicked list items to be converted into a strings and transported into a 3rd activity where i can display those.
when i try to display them this shows in the text view where the clicked text item should have appeared:
this is code for the first activity:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.internal.Objects;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class TicketCategory extends AppCompatActivity {
public static String Category;
public String getCategory() {
return Category;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ticket_category);
populateTicketCategoryList();
final ListView listView = (ListView) findViewById(R.id.lvTicketCategory);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (i == 0) {
Category = listView.getItemAtPosition(i).toString();
Intent intent = new Intent(TicketCategory.this, Subcategory.class);
startActivity(intent);
}
}
});
}
private void populateTicketCategoryList()
{
ArrayList<CompTicketCategory> arrayOfTicket = CompTicketCategory.getTicket();
CompTicketCategoryAdapter adapter = new CompTicketCategoryAdapter(this, arrayOfTicket);
ListView listView = (ListView) findViewById(R.id.lvTicketCategory);
listView.setAdapter(adapter);
}
}
the code for the second activity is:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class Subcategory extends AppCompatActivity {
public String Category;
public static String Subcat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subcategory);
populateSubcategoryList();
final ListView listView = (ListView) findViewById(R.id.lvSubcategory);
ArrayAdapter arrayAdapter = new ArrayAdapter<String>(Subcategory.this, android.R.layout.simple_list_item_1,arrayList);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Subcat = listView.getItemAtPosition(i).toString();
Intent intent = new Intent(Subcategory.this, SubmitTicket.class);
startActivity(intent);
}
});
and this is the code for the activity where both of the clicked items should be displayed:
public class SubmitTicket extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_submit_ticket);
Spinner spinner = (Spinner) findViewById(R.id.spinner_priority);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.priority_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
final Button butt = findViewById(R.id.submit);
butt.setOnClickListener(new View.OnClickListener()
{
public void onClick (View view){
Toast.makeText(getApplicationContext(), "The ticket has been submitted", Toast.LENGTH_SHORT).show();
}
});
TextView textView = (TextView)findViewById(R.id.Category_submit_report);
textView.setText(TicketCategory.Category);
TextView tv = (TextView)findViewById(R.id.Subcategory_submit_report);
tv.setText(Subcategory.Subcat);
}
Please help me. i would appreciate any output. thanks!
UPDATE:
after trying
CompTicketCategory model = listView.getItemAtPosition(i);
Category=model.Category; // your Category variable
Category=model.getCategory();
this error is shown;
screenshot
You can use Intent Extra Feature.
In the First Activity,
Intent intent = new Intent(Subcategory.this, SubmitTicket.class);
switch1.putExtra("deviceID", listView.getItemAtPosition(i).toString(););
startActivity(intent);
Then Next activity recall them,
Intent intent = getIntent();
String data = intent.getStringExtra("data");
Try this in your TicketCategory actvity
Use this:
CompSubcategory model = listView.getItemAtPosition(i);
Category=model.Category; // your Category variable
Category=model.getCategory(); // or use getter setter method
Instead of this:
Category = listView.getItemAtPosition(i).toString();

Cant display the item of my List View

I have a project for my school making a FAB and floating label.
The question is, the item on the list view is not diplayed and i having a hard time fixing on that.
I have two java class. MainActivity.java and MyCustomAdapter.java
Here is code for MainActivity.java
package com.example.sugara.floatingaction_mario;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.preference.DialogPreference;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private ListView myList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myList = (ListView) findViewById(R.id.list);
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, "Row " + position + " clicked", Toast.LENGTH_SHORT).show();
}
});
FloatingActionButton FAB = (FloatingActionButton) findViewById(R.id.fab);
FAB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showInputDialog();
}
});
final ArrayList list = new ArrayList<>();
list.add("Richard Felmon age 23");
list.add("Nestor Mersy age 44");
list.add("Bruto Char age 12");
list.add("Filemon Mandela age 33");
list.add("Sukyuu Nirasu age 39");
// final MainActivity adapter = new MyCustomAdapter(MainActivity.this, list);
// myList.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
protected void showInputDialog() {
LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this);
View promptView = layoutInflater.inflate(R.layout.activity_second, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogBuilder.setView(promptView);
alertDialogBuilder.setCancelable(false).setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(getApplicationContext(), "Data saved ", Toast.LENGTH_LONG).show();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
}
And here is my MyCustomAdapter.java
package com.example.sugara.floatingaction_mario;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
public class MyCustomAdapter extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
//Displaying TextInputLayout Error
TextInputLayout lNameLayout = (TextInputLayout) findViewById(R.id.lNameLayout);
lNameLayout.setErrorEnabled(true);
lNameLayout.setError("Min 2 chars required");
//Displaying EditText Error
EditText age = (EditText) findViewById(R.id.age);
age.setError("Required");
}
}
I have tried making adapter for listview but when i do so
It is clashing with
public class MyCustomAdapter extends AppCompatActivity {
Can you help me fixing this and make the input displayed on the listview too?
I am sorry if it's confusing, it's my first time posting a question like this
If you want only text in the ListView than you may not customize the Adapter Class.
Please use this. This will help you.
Create layout with TextView(layout_list.xml)
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="20sp" >
</TextView>
Modify MainActivity.java like this.
...
final ArrayList list = new ArrayList<>();
list.add("Richard Felmon age 23");
list.add("Nestor Mersy age 44");
list.add("Bruto Char age 12");
list.add("Filemon Mandela age 33");
list.add("Sukyuu Nirasu age 39");
myList.setAdapter(new ArrayAdapter<String>(this, R.layout.layout_list, list));
Your Adapter must extend an Adapter class of Android. Try
public class MyCustomAdapter extends BaseAdapter {
and then implementing the necessary methods.

calling dialog fragment from my fragment

I am trying to call a DialogFragment from my Fragment class. I have an EditText, and would like to call my DialogFragment class in the onClickListener of the EditText I have set up.
I am getting an error in the onClick with the code I have set up trying to call the DialogFragment.
I am getting an error on "show" stating "The method show(FragmentManager, String) in the type DialogFragment is not applicable for the arguments (FragmentManager, String)" and an error on "new Instance" stating "The method newInstance() is undefined for the type MyDialogFragment"
Here's my code:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View root = (View) inflater.inflate(R.layout.fragment_profile_fragment, container, false);
setListenerOnWeight(root);
button(root);
return root;
}
public void setListenerOnWeight(View v) {
EditText Weight = (EditText) v.findViewById(R.id.Weight_up);
Weight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
weight_frag dialog = new weight_frag.newInstance();
dialog.show(getFragmentManager(), "fragmentDialog");
}
});
}
for my DialogFragment class:
package com.the.healthescort;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.*;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class weight_frag extends DialogFragment {
Context mContext;
public weight_frag() {
mContext = getActivity();
}
public static weight_frag newInstance() {
weight_frag f = new weight_frag();
return f;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext);
alertDialogBuilder.setTitle("Set Wallpaper?");
alertDialogBuilder.setMessage("Are you sure?");
//null should be your on click listener
alertDialogBuilder.setPositiveButton("OK", null);
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return alertDialogBuilder.create();
}
}
i think you should replace
import android.app.Fragment;
with
import android.support.v4.app.Fragment;
in your "my Fragment" class
and you should also provide a method with name newInstance in your dialogfragment class like below :
public static weight_frag newInstance(){
weight_frag frag = new weight_frag();
return frag;
}
please follow java naming conventions by using capital letter for the starting letter (WeightFragment)

Categories