displaying different messages depending on parameters - java

I'm new to android development. I have 10 different buttons and I want to display a toast for each one of them. The message is something like:
"This is the button: " + numButton
Where numButton is a prop passed to the function. This is the function code:
public void displayMensaje(View v) {
Toast.makeText(ActividadUno.this, "Test", Toast.LENGTH_SHORT).show();
}
And this is the xml:
<Button
android:id="#+id/button11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="30dp"
android:layout_marginLeft="30dp"
android:layout_marginTop="400dp"
android:text="churro"
android:onClick="displayMensaje"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

You can cast the View in Button and get the text of button.
Something like this:
public void displayMensaje(View v) {
Button button = (Button) v;
String title = button.getText();
String message = "Test " + title;
Toast.makeText(ActividadUno.this, message, Toast.LENGTH_SHORT).show();
}
Edit:
According to my understanding from your comment below, you have multiple buttons in your activity, and you want to display different values on clicking different buttons.
You can have a Map with keys as button titles and values as nutrition values.
Below is a general example of how you can achieve this:
public class MyActivity extends Activity {
// Your Message Format
private static final String MSG_FORMAT = "Item Name: %s\n"
+ "Fat: %s\n"
+ "Protein: %s\n"
+ "Calories: %s";
// A Map to hold info of all items
// Key = button title
// Value = Array containing item info
private Map<String, String[]> info = new HashMap();
// Assuming you have 3 buttons in your activity
private Button btnMilk;
private Button btnEggs;
private Button btnChicken;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activity);
btnMilk = (Button) findViewById(R.id.btn_milk);
btnEggs = (Button) findViewById(R.id.btn_eggs);
btnChicken = (Button) findViewById(R.id.btn_chicken);
// 0 = Fat, 1 = Protein, 2 = Calories
String[] milkInfo = new String[]{"12", "20", "125"};
String[] eggsInfo = new String[]{"10", "50", "205"};
String[] chickenInfo = new String[]{"50", "5", "500"};
// load your Map with the data
info.put(btnMilk.getText(), milkInfo);
info.put(btnEggs.getText(), eggsInfo);
info.put(btnChicken.getText(), chickenInfo);
}
public void displayMessage(View v) {
Button button = (Button) v;
String title = button.getText();
// Get item info from your Map
String[] itemInfo = info.get(title);
// Create message using the format and values from the array
String message = String.format(MSG_FORMAT, title, itemInfo[0], itemInfo[1], itemInfo[2]);
Toast.makeText(MyActivity.this, message, Toast.LENGTH_SHORT).show();
}
}
Hope this helps

Related

GetText() for a chipgroup (entry)

I'm quite new in java/android and i need for a project to implement chip (entry). I followed a tutorial and the chip works. what i made
XML
<Button
android:id="#+id/email_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="buttonClick"
android:text="Ajouter"
android:textSize="10sp"
app:layout_constraintBottom_toTopOf="#+id/chip_group"
app:layout_constraintLeft_toRightOf="#+id/fields_2_form"
app:layout_constraintTop_toBottomOf="#+id/title_field_3">
</Button>
<com.google.android.material.chip.ChipGroup
android:id="#+id/chip_group"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="#+id/fields_2_form">
</com.google.android.material.chip.ChipGroup>
Activity
public void buttonClick(View view) {
final EditText fieldForm2 = findViewById(R.id.fields_2_form);
final ChipGroup chipGroup = findViewById(R.id.chip_group);
final Button emailButton = findViewById(R.id.email_button);
final Chip chip = new Chip(this);
ChipDrawable drawable = ChipDrawable
.createFromAttributes(this, null, 0, R.style.Widget_MaterialComponents_Chip_Entry);
chip.setChipDrawable(drawable);
chip.setCheckable(false);
chip.setClickable(false);
chip.setChipIconResource(R.drawable.ic_fingerprint_black_24dp);
chip.setIconStartPadding(3f);
chip.setPadding(60, 10, 60, 10);
chip.setText(fieldForm2.getText().toString());
// remove chip on click on the -
chip.setOnCloseIconClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chipGroup.removeView(chip);
}
});
if (!EmailValid(fieldForm2.getText().toString())) {
Toast.makeText(getApplicationContext(),
"Veuillez rentrer un email valide",
Toast.LENGTH_LONG).show();
fieldForm2.setText("");
} else {
chipGroup.addView(chip);
fieldForm2.setText("");
}
}
Well but my problem is when i need to get all the typed emails from the chip for another activity.
I tried to do it in this method :
public Intent getFormInfos() {
TextView mEditTextHour = findViewById(R.id.fields_1_form);
final Spinner spin = (Spinner) findViewById(R.id.Spinner);
final ChipGroup chipGroup = findViewById(R.id.chip_group);
//FIXME
String chiptext = chipGroup.INEEDTOGETCHIPTEXTHERE();
String myEditedText1 = mEditTextHour.getText().toString();
String spinnerText = spin.getSelectedItem().toString();
Intent intent = new Intent(this, ActivityListMareu.class);
ApiService.getmReunions().add(new Reunion(myEditedText1, spinnerText, chiptext));
return intent;
}
I need to do something like chipgroup.getText() but it doesn't work i tried some stuff but i'm really confused with chip and actually i've no idea how to make it.
Does someone have an idea for this?
(sorry for my bad english)
Using this you can get all the text set over all Chip in that ChipGroup.
ArrayList<String> emails = new ArrayList<>();
for (int i = 0; i < chipGroup.getChildCount(); i++) {
String email = ((Chip) chipGroup.getChildAt(i)).getText().toString();
emails.add(email);
}
In your case if you have only one chip in chipGroup you can directly :
if (chipGroup.getChildCount() > 0) {
CharSequence yourText = ((Chip) chipGroup.getChildAt(0)).getText();
}
This is in Kotlin but you can essentially do a transform on the getChildren() just like any collection/sequence:
val emails = chipGroup.children.map {
(it as Chip).text.toString()
}.toList()

Firing an action to be executed when a button is pressed

Just started learning Java for application development through Android Studio. Creating an application that collects the user's inputs of which include their Name and Age of which when a Submition button is clicked the output is a string based on their Age range. code below:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Adding Action to the Button
Button BtnSubmit = findViewById(R.id.BtnSubmit);
BtnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String TbName = "";
int TbAge =0;
String TxtOuput;
if (TbAge>0 && TbAge<=18)
{
TxtOuput = TbName + ("You Are Still A Child");
}
else if(TbAge>18 && TbAge<=64)
{
TxtOuput = TbName + ("You Are Grown");
}
else if(TbAge>64)
{
TxtOuput = TbName + ("You Are About To Die") + ("R.I.P");
}
}
});
}
}
Tried various methods from google, youtube and other sources but the application will not still execute an output.
Application layout/blueprint:
You are not getting your text fields values in a variable anywhere in code you have shared. Similarly you are not setting those values back to Status text field as well.
So it should be something like this:
If I assume you have firstEditText EditText View for name, secondEditText for age, and resultTextView for status, then your code would be something like below:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Adding Action to the Button
Button BtnSubmit = (Button)findViewById(R.id.BtnSubmit);
EditText firstEditText = (EditText) findViewById(R.id.firstEditText);
EditText secondEditText = (EditText) findViewById(R.id.secondEditText);
TextView resultTextView = (TextView) findViewById(R.id.resultTextView);
BtnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String TbName = firstEditText.getText();
int TbAge = Integer.parseInt(secondEditText.getText().toString());
String TxtOuput;
if (TbAge>0 && TbAge<=18)
{
TxtOuput = TbName + ("You Are Still A Child");
}
else if(TbAge>18 && TbAge<=64)
{
TxtOuput = TbName + ("You Are Grown");
}
else if(TbAge>64)
{
TxtOuput = TbName + ("You Are About To Die") + ("R.I.P");
}
resultTextView.setText(TxtOuput);
}
});
}
}
Try this and let me know
AS per your question, you want user to add his name and age in the editText fields. When clicked on SUBMIT button, that entered data should be displayed on the next screen(activity).
To achieve this:
use 2 editText fields and 1 button in your xml layout file.
Problem:
You have added only button view in your layout file and not the editText.
Let me know if you want the code for the same then.
Best and easy way of using onclick listener,
In your xml layout,
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activity.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onclick="goToMethod"/>
</LinearLayout>
In your activity,
class MainActivity extends Activity{
public void goToMethod(View view){
//do your code here
}
}
Note: In tools:context you should mention the activity where you are using layout and onclick

Android/MySQL: How to a radio button is checked based from value at MySQL

Currently I have trouble based on my question above. I Have two radio button in one radio group. The first radio button is "Approved" and the second radio button is "Rejected". Example, if I clicked the radio button "Approved", the value from that checked radio button will save to MySQL. Then, if I want to display back the value of Radio button, how will the radio button "Approved" is display as Checked? (don't want to display back as TextView).
Below is my code on how I get all the value from edit text to text view.
This code is retrieve from database and display as textView.
etName = findViewById(R.id.etName);
etBadgeID = findViewById(R.id.etBadgeID);
etDepartment = findViewById(R.id.etDepartment);
etFactory = findViewById(R.id.etFactory);
etPosition = findViewById(R.id.etPosition);
etReviewer = findViewById(R.id.etReviewer);
etTitle = findViewById(R.id.etTitle);
etMonth = findViewById(R.id.etMonth);
etYear = findViewById(R.id.etYear);
etSuggestwill = findViewById(R.id.etSuggestwill);
etPresent = findViewById(R.id.etPresent);
etDetails = findViewById(R.id.etDetails);
etBenefit = findViewById(R.id.etBenefit);
imgAttach = findViewById(R.id.imgAttach);
rgStatus = findViewById(R.id.rgStatus);
etComment = findViewById(R.id.etComment);
Intent intent = getIntent();
User user = (User) intent.getSerializableExtra("user");
etName.setText(user.getName());
etBadgeID.setText(user.getBadgeid());
etDepartment.setText(user.getDepartment());
etFactory.setText(user.getFactory());
etPosition.setText(user.getPosition());
etReviewer.setText(user.getReviewer());
etTitle.setText(user.getTitle());
etMonth.setText(user.getMonth());
etYear.setText(user.getYear());
etSuggestwill.setText(user.getSuggestionwill());
etPresent.setText(user.getPresent());
etDetails.setText(user.getDetails());
etBenefit.setText(user.getBenefit());
imgAttach.setImageBitmap(base64ToBitmap(user.getPhoto()));
etComment.setText(user.getComment());
This is how I store value radio button at the database (at Submit Button)
int selectedId = rgStatus.getCheckedRadioButtonId();
radioButton = findViewById(selectedId);
final String status = radioButton.getText().toString();
update(status);
Method for update(status)
private void update(final String status){
class updateClass extends AsyncTask<String,Void,String> {
private ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading =
ProgressDialog.show(NeedApproval.this,"Updating.....",null,true,true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
}
#Override
protected String doInBackground(String... params) {
//creating request handler object
RequestHandler requestHandler = new RequestHandler();
//creating request parameters
HashMap<String, String> data = new HashMap<>();
data.put("status",params[0]);
//returing the response
return requestHandler.sendPostRequest(URLs.URL_UPDATE, data);
}
}
updateClass ulc = new updateClass();
ulc.execute(status);
}

button doesn't click in android studio

private Button mfactbutton;
private TextView mfacttext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_fun_fact);
Button mfactbutton = (Button) findViewById(R.id.button);
TextView mfacttext = (TextView) findViewById(R.id.textView2);
// now we need to make out button to click
View.OnClickListener Listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] facts = {
"Ants stretch when they wake up in the morning.",
"Ostriches can run faster than horses.",
"Olympic gold medals are actually made mostly of silver.",
"You are born with 300 bones; by the time you are an adult you will have 206.",
"It takes about 8 minutes for light from the Sun to reach Earth.",
"Some bamboo plants can grow almost a meter in just one day.",
"The state of Florida is bigger than England.",
"Some penguins can leap 2-3 meters out of the water.",
"On average, it takes 66 days to form a new habit.",
"Mammoths still walked the earth when the Great Pyramid was being built." };
String fact = "";
// randomly select a fact
Random randomGenerator = new Random();
int randomNumber = randomGenerator.nextInt(facts.length);
fact = facts[randomNumber] + "";
}
};
mfactbutton.setOnClickListener(Listener);
}
}
Hey everyone! i need help! my button doesn't just simply clicl!!!!! heeeeeeeeelp!i'm just trying to make a simple button that changes the textview2 with each click! at first it was working but now it started not to work.
Your Button clicked properly but the main thing is you did not set fact value to TextView.
#. As you have declared Button and TextView outside onCreate(), no need to declare it again inside onCreate().
Use:
mfactbutton = (Button) findViewById(R.id.button);
mfacttext = (TextView) findViewById(R.id.textView2);
Instead of:
Button mfactbutton = (Button) findViewById(R.id.button);
TextView mfacttext = (TextView) findViewById(R.id.textView2);
#. In onClick() method show fact value on TextView or show Toast message:
// TextView
mfacttext.setText(fact);
// Toast
Toast.makeText(getApplicationContext(), "Fact: " + fact, Toast.LENGTH_SHORT).show();
Here is the working code:
public class MainActivity extends AppCompatActivity {
private Button mfactbutton;
private TextView mfacttext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mfactbutton = (Button) findViewById(R.id.button);
mfacttext = (TextView) findViewById(R.id.textView2);
// now we need to make out button to click
View.OnClickListener Listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] facts = {
"Ants stretch when they wake up in the morning.",
"Ostriches can run faster than horses.",
"Olympic gold medals are actually made mostly of silver.",
"You are born with 300 bones; by the time you are an adult you will have 206.",
"It takes about 8 minutes for light from the Sun to reach Earth.",
"Some bamboo plants can grow almost a meter in just one day.",
"The state of Florida is bigger than England.",
"Some penguins can leap 2-3 meters out of the water.",
"On average, it takes 66 days to form a new habit.",
"Mammoths still walked the earth when the Great Pyramid was being built." };
String fact = "";
Random randomGenerator = new Random();
int randomNumber = randomGenerator.nextInt(facts.length);
fact = facts[randomNumber] + "";
mfacttext.setText(fact);
Toast.makeText(getApplicationContext(), "Fact: " + fact, Toast.LENGTH_SHORT).show();
}
};
mfactbutton.setOnClickListener(Listener);
}
}
OUTPUT:
Do you set your selected fact to your textView ? Add
mfacttext.setText(fact);
after selecting your random fact.
Random randomGenerator = new
int randomNumber = randomGenerator.nextInt(facts.length);
fact = facts[randomNumber] + "";
mfacttext.setText(fact);
use this
mfactbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Your code goes here
}
});
Hi I just created a simple project. if you click on the button, it will generate random text on the textview2.
MainActivity.java
public class MainActivity extends AppCompatActivity {
TextView secondTextView;
String[] Textlist = { "Hello man ", "sonam", "tashi","i am man","hellow world"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
secondTextView = (TextView) findViewById(R.id.textView2);
Button mybtn = (Button) findViewById(R.id.btn);
mybtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
changeTextView_two_text();
}
});
}
private void changeTextView_two_text() {
Random random = new Random();
String rand = Textlist[random.nextInt(Textlist.length)];
// String randomText = TextList[random.nextInt(TextList.length)];
secondTextView.setText(rand);
}
}
and activity_main.xml
<LinearLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.hello.googlemap.MainActivity">
<Button
android:id="#+id/btn"
android:text="click me"
android:layout_width="368dp"
android:layout_height="wrap_content"
tools:layout_editor_absoluteY="0dp"
tools:layout_editor_absoluteX="8dp" />
<TextView
android:gravity="center"
android:id="#+id/textView2"
android:text="no text"
android:layout_width="match_parent"
android:layout_height="wrap_content"/></LinearLayout>
Hope this helps you.

Can not load data to ListView in Activity

I'm using json to load data in Activity class with content following as:
My Activity class:
public class CategoryCarActivity extends ListActivity {
ConnectionDetector cd;
AlertDialogManager alert = new AlertDialogManager();
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
ArrayList<Category> carsList = new ArrayList<Category>();
JSONArray manufacturers = null;
String manufacturer_id, manufacturer_name;
private static final String URL_MANUFACTURERS = "MyURL";
// ALL JSON node names
private static final String TAG_CARS = "cars";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_MANUFACTURER = "name";
private static final String TAG_PRICE = "price";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(CategoryCarActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
Intent i = getIntent();
manufacturer_id = i.getStringExtra("id");
carsList = new ArrayList<Category>();
// Loading tracks in Background Thread
new LoadTracks().execute();
// get listview
ListView lv = getListView();
/**
* Listview on item click listener
* SingleTrackActivity will be lauched by passing manufacturer id, car id
* */
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
// On selecting single track get car information
Intent i = new Intent(getApplicationContext(), DetailListCarActivity.class);
// to get car information
// both manufacturer id and car is needed
String manufacturer_id = ((TextView) view.findViewById(R.id.manufacturer_id)).getText().toString();
String car_id = ((TextView) view.findViewById(R.id.car_id)).getText().toString();
Toast.makeText(getApplicationContext(), "Manufacturer Id: " + manufacturer_id + ", Car Id: " + car_id, Toast.LENGTH_SHORT).show();
i.putExtra("manufacturer_id", manufacturer_id);
i.putExtra("car_id", car_id);
startActivity(i);
}
});
}
/**
* Background Async Task to Load all tracks under one album
* */
class LoadTracks extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CategoryCarActivity.this);
pDialog.setMessage("Loading selected car ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting tracks json and parsing
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// post album id as GET parameter
params.add(new BasicNameValuePair(TAG_ID, manufacturer_id));
// getting JSON string from URL
String json = jsonParser.makeHttpRequest(URL_MANUFACTURERS, "GET",
params);
// Check your log cat for JSON reponse
Log.d("Category List JSON: ", json);
try {
JSONObject jObj = new JSONObject(json);
if (jObj != null) {
String manufacturer_id = jObj.getString(TAG_ID);
manufacturer_name = jObj.getString(TAG_MANUFACTURER);
manufacturers = jObj.getJSONArray(TAG_CARS);
if (manufacturers != null) {
// looping through All cars
for (int i = 0; i < manufacturers.length(); i++) {
JSONObject c = manufacturers.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
// track no - increment i value
String track_no = String.valueOf(i + 1);
String name = c.getString(TAG_NAME);
String price = c.getString(TAG_PRICE);
// creating new HashMap
// HashMap<String, String> map = new HashMap<String, String>();
Category category = new Category();
category.setManufacturer_id(manufacturer_id);
category.setId(id);
category.setName(name);
category.setPrice(price);
// adding each child node to HashMap key => value
/*
map.put("manufacturer_id", manufacturer_id); // note here
map.put(TAG_ID, car_id);
map.put("track_no", track_no + ".");
map.put(TAG_NAME, name);
map.put(TAG_PRICE, price);
*/
// adding HashList to ArrayList
// carsList.add(map);
carsList.add(category);
}
} else {
Log.d("Manufacturers: ", "null");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String result) {
pDialog.dismiss();
ListAdapter adapter = new ArrayAdapter<Category>(
CategoryCarActivity.this, // the context
R.layout.list_item_categorys, // Simple list item - will toString() your data
carsList // The arraylist
);
// updating listview
setListAdapter(adapter);
}
}
}
list_item_categorys.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/manufacturer_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<!-- Song id / Hidden by default -->
<TextView
android:id="#+id/car_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<TextView
android:id="#+id/track_no"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="15dip"
android:paddingLeft="5dip"
android:paddingTop="15dip"
android:textColor="#000000"
android:textSize="16dip"
android:layout_alignParentLeft="true"/>
<TextView
android:id="#+id/manufacturer_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="15dip"
android:paddingLeft="5dip"
android:paddingTop="15dip"
android:textColor="#000000"
android:textSize="16dip"
android:layout_toRightOf="#+id/track_no"/>
<TextView
android:id="#+id/price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:paddingLeft="3dip"
android:paddingRight="6dip"
android:textColor="#9ed321" />
I have debugged and check Logcat and see that data has loaded and everything normal, but don't know why data can not load to ListView
updated
Logcat:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.totoroads.android.app, PID: 4697
java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView
at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:393)
at android.widget.ArrayAdapter.getView(ArrayAdapter.java:369)
How to fix this problem?? thank you
You're not providing your list to the list view. You need to add your list to your list view with an adapter. This tutorial should help walk you through the process. http://www.vogella.com/tutorials/AndroidListView/article.html
In your postExecute of your asyncTask you can than call adapter.notifyDataSetChanged(). And your view will update with the new list content.
This code looks really similar... maybe copy the rest of it?
You need an Adapter for your data.
protected void onPostExecute(String result) {
// dismiss the dialog after getting all tracks
pDialog.dismiss();
ListAdapter adapter = new ArrayAdapter<Category>(
CategoryCarActivity.this, // the context
android.R.layout.simple_list_item_1, // Simple list item - will toString() your data
carList // The arraylist
);
// updating listview
setListAdapter(adapter);
}
You can also make a subclass of ArrayAdapter<Category> if you really want to customize a layout.
Adding to Ben's answer, you need to set the list to the listview adapter after the asynctask completes its background functionality i.e in onPostExecute() method of the asynctask.
Need to set the list view as suggested by Ben in onPostExecute().
ListView listView = (ListView) findViewById(R.id.your_list_view_id);
listView.getAdapter().notifyDataSetChanged();

Categories

Resources