The textview is empty when I use substring - android

I am doing an application in android. The application saves a quote or an expression in a textfield. The user has the opportunity to change this text. But I wanted that when the quote is appeared in the TextView, it is not appeared at all. I wanted only the first 5 characters of the quote to be appeared. I try to do this using the substring, but when I open the TextView nothing appears. The TextView is empty. What can I do?
Can anyone help me , please.
Thanks in advance.
This is the line where I use substring:
ListAdapter adapter = new SimpleAdapter( Quote.this,quoteList, R.layout.quote_entry, new String[] { "quoteId", "textQuote".substring(0, 4)}, new int[] {R.id.quoteId, R.id.textQuote});
And here is the entire class
package com.example.prova1;
/**This class is the page of quotes*/
import java.util.ArrayList;
import java.util.HashMap;
import android.app.ListActivity;
import com.example.prova1.Database;
import com.example.prova1.EditQuote;
import com.example.prova1.AddQuote;
import com.example.prova1.R;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SimpleAdapter;
import android.widget.ListView;
public class Quote extends ListActivity {
Intent intent;
TextView quoteId;
Database quotedatabase = new Database(this);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.quote_main);//define that the interface used is quote_main
//Store data from database in an array list
ArrayList<HashMap<String, String>> quoteList = quotedatabase.getAllItems();
//Check if there are quotes to display
if(quoteList.size()!=0) {
ListView listView = getListView();
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
quoteId = (TextView) view.findViewById(R.id.quoteId);
String itemIdValue = quoteId.getText().toString();
Intent theIndent = new Intent(getApplication(),ShowQuote.class);
theIndent.putExtra("quoteId", itemIdValue);
finish();
startActivity(theIndent);
}
});
// Here we use ListAdapter as a bridge between ListView and the data of ListView
ListAdapter adapter = new SimpleAdapter(
Quote.this,quoteList,
R.layout.quote_entry,
new String[] {
"quoteId",
"textQuote".substring(0, 4)
},
new int[] {
R.id.quoteId,
R.id.textQuote}
);
setListAdapter(adapter);
}
}
}

I don't have the SDK installed at the moment to test your code, but I do have a couple suggestions.
First: Try the code without the substring, and see if that works.
Second: If that works, then move the substring operation to the line before and pass in the result to the SimpleAdapter.
I say this because I have the feeling that the substring is not actually your problem. And this is just a good way to test that.
I'd also check your layout "R.layout.quote_entry" and make sure there isn't anything weird going on with that. Such as you having "R.id.textQuote" actually being 'gone' and another TextView being visibly shown, etc. I had this problem once. I had two EditText fields, and only one of them was being shown, so the Activity looked right, but wasn't behaving properly.

Related

How to disable a single row and change its background color in a listview, without a button (or a method if possible)?

The title of this post says it all.
This code works without any problems:
package abc.AvailableCars;
import android.graphics.Color;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class carListActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.car_list_layout);
final ListView carListview = (ListView) findViewById(R.id.list_view);
final Button dButton = (Button) findViewById(R.id.disable_button);
String[] cars = {"Maxima GXE", "Passat", "Focus SE", "Mazda6", "Avalon", :Sentra GXE"};
final List<String> list_of_cars = new ArrayList<String>(Arrays.asList(cars));
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, list_of_cars);
carListview.setAdapter(arrayAdapter);
dButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int chosenRow = 3;
carListview.getChildAt(3).setEnabled(false);
carListview.getChildAt(3).setBackgroundColor(Color.parseColor("#3f51b5"));
}
});
}
}
This is in my listview .xml file:
<Button
android:id="#+id/disable_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Disable A Row"
/>
But, when I comment-out everything that belongs to the button, like below, and the Car List class is called, the app crashes with the error in the Logcat:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setEnabled(boolean)' on a null object reference:
final ListView carListview = (ListView) findViewById(R.id.list_view);
//final Button dButton = (Button) findViewById(R.id.disable_button);
String[] cars = {"Maxima GXE", "Passat", "Focus SE", "Mazda6", "Avalon"};
final List<String> list_of_cars = new ArrayList<String>(Arrays.asList(cars));
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, list_of_cars);
carListview.setAdapter(arrayAdapter);
//dButton.setOnClickListener(new View.OnClickListener() {
//#Override
//public void onClick(View v) {
int chosenRow = 3;
carListview.getChildAt(chosenRow).setEnabled(false);
carListview.getChildAt(chosenRow).setBackgroundColor(Color.parseColor("#3f51b5"));
}
//});
}
//}
I'm not an Android newbie anymore, but this is eluding me.
I want the chosen row to be disabled and the color set as soon as the listview is shown.
How can I do this programmatically without a button?
I have tried every variation I can think of, getView(), even a fake click.
Just in case it makes a difference, this code is in a separate class and file than the MainActivity.java file, and is called in that file.
There has to be a simple answer. What do I need to change?
Please be verbose.
Thank you.
You are calling carListview.getChildAt(chosenRow) when you set up your list view, in onCreate. Your list view is not ready yet. Try moving this code to your onResume - should look something like this:
#Override
public void onResume(){
super.onResume();
arrayAdapter.notifyDataSetChanged();
int chosenRow = 3;
carListview.getChildAt(chosenRow).setEnabled(false);
carListview.getChildAt(chosenRow).setBackgroundColor(Color.parseColor("#3f51b5"));
}
This is a pretty simple case - your chosenRow number is generated by you. You might need a custom Adapter if you need it to be algorithmic or user-driven. Have a look at this tutorial.
From my understanding, since listViews are views, they have to be Overridden for some things to be changed in them.
I chose not to disable the required rows, but check for them in code.
The complete code that works is below.
Some credit goes to Raghunandan for his/her answer at-
Android - Change background color of specific item of ListView
Again, sorry, but the indentation of the code wouldn't work correctly for some reason.
import android.graphics.Color;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CarListActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.car_list_layout);
final ListView carListview = (ListView) findViewById(R.id.list_view);
String[] cars = {"European Cars:", "Mercedes", "Passat", "Bently", "Porsche", "BMW", "Yugo","Land Rover",
"Japanese Cars:", "Maxima GXE", "Mazda6", "Avalon", "Toyota", "Honda", ""};
final List<String> list_of_cars = new ArrayList<String>(Arrays.asList(cars));
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, list_of_cars);
//------------------------------------------
carListview.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list_of_cars) {
// Since listViews are views, they have to be Overrdden for some things to be changed in them.
#Override
public View getView(int rowPosition, View convertView, ViewGroup parent) {
View row = super.getView(rowPosition, convertView, parent);
//------------------------------------------
// This works. I have only tried this for two rows, the two I wanted. I expected this line to crash the app, but it didn't.
if(getItem(rowPosition).equals("European Cars:") || getItem(rowPosition).equals("Japanese Cars:")) {
// Make the two rows have a white background color.
row.setBackgroundColor(Color.WHITE); // this command WORKS fine by itself.
// row.setEnabled(false); this command caused "bleeding" over into other rows, so I will check for the rows in a condition.
} // both of the getItems end here.
else {
// All of the other rows should have this color.
row.setBackgroundColor(Color.parseColor("#EEE8AA"));
// the default color
} // else ends here.
//------------------------------------------
return row;
//------------------------------------------
} // getView ends here.
}); // carListview.setAdapter ends here.
} // onCreate ends here.
} // CarListActivity ends here.
Thanks, and I hope this helps others.

Dynamic List app add button not working

I wrote an exercise android app which consists of a text entry, an add button, and a dynamic list. Users are supposed to be able to type a string into the text entry, click on add button, and add it to the list. However, when I run this script on the emulator, nothing happens when I click on the add button. Checking the logcat doesn't help, because no logs appear when clicking on the button either. I also tried adding a breakpoint, but, again, nothing happens when I try to step over. Can someone help me on this please? I'd greatly appreciate it. Thanks.
package p.listviewexerice2;
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.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
Button bt;
EditText et;
ListView lv;
ArrayAdapter<String> adapter;
ArrayList<String> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt = (Button) findViewById(R.id.button);
et = (EditText) findViewById(R.id.editText);
lv = (ListView) findViewById(R.id.listView);
list = new ArrayList<>();
list.add("x");
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Toast.makeText(getBaseContext(),list.get(position),Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onClick(View v){
if(v==bt){
String name = et.getText().toString();
if(name.isEmpty()){
Toast.makeText(getBaseContext(),"Empty entry",Toast.LENGTH_SHORT).show();
}
else{
list.add(name);
adapter.notifyDataSetChanged();
}
}
}
}
Can you delete lv.setOnItem.. code block and try again ?
Because you have already implements from onClickListener, so your button call the method onClick()
Instead of this:
list.add(name);
Do this:
adapter.add(name);
Explanation: you create the adapter with parameter list, allright. But since then adapter manages it's own internal list. Adapter also has built-in methods "add()" and "remove()", to manage that internal list.
Your code is almost fine, just 1 thing is missing. You have not registered the click event for your button bt. And without registering the click event the system will not be able to execute the code for onClick(View v).
so just add the below code in your onCreate()
bt.setOnClickListener(this);

Is there an easier way to get what im trying to achieve here?

I made an app which displays some information about some products, I achieved this by putting the brands in an arraylist on my main activity, and then after the user selects a brand he can choose a specific model, I did this by making a global xml file, and a class for each model with Strings and ints as the details, now the thing is, there are potentially hundreds and even over thousand models, is there an easier way to achieve this? like putting ALL of the data in one class and just pull it from it? or would it make things messier?
just to let you guys know that i'm a total beginner.
This is my code:
main activity shows a list of brands:
package com.example.ofir.myapplication;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.example.ofir.myapplication.lists.bmwList;
import com.example.ofir.myapplication.lists.ktmList;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ArrayList<Brands> brands = new ArrayList<>();
brands.add(new Brands("KTM", ContextCompat.getColor(this, R.color.colorOrange)));
brands.add(new Brands("BMW", ContextCompat.getColor(this, R.color.colorPrimary)));
brands.add(new Brands("Suzuki", ContextCompat.getColor(this, R.color.colorPrimary)));
BrandAdapter itemsAdapter = new BrandAdapter(this, brands);
ListView listView = (ListView) findViewById(R.id.brandlist);
listView.setAdapter(itemsAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(position == 0) {
Intent intent = new Intent(MainActivity.this, ktmList.class);
startActivity(intent);
}else if (position == 1) {
Intent intent2 = new Intent(MainActivity.this, bmwList.class);
startActivity(intent2);
}
}
});
}
}
each brands opens up models list:
for testing purposes I just set 2 brands with lists.
package com.example.ofir.myapplication.lists;
import com.example.ofir.myapplication.R;
import com.example.ofir.myapplication.models.dukeSmall;
import com.example.ofir.myapplication.models.smc;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import static android.media.CamcorderProfile.get;
public class ktmList extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.models_list);
final ArrayList<String> ktmlist = new ArrayList<String>();
ktmlist.add("Duke 125");
ktmlist.add("Duke 200");
ktmlist.add("Duke 390");
ktmlist.add("Duke 690");
ktmlist.add("RC 125");
ktmlist.add("RC 200");
ktmlist.add("RC 390");
ktmlist.add("RC8");
ktmlist.add("SMC-R 690");
ktmlist.add("SMR 990");
ktmlist.add("SuperDuke 990");
ktmlist.add("SuperDuke 1290");
final ArrayAdapter<String> itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, ktmlist);
ListView listView = (ListView) findViewById(R.id.models_list);
listView.setAdapter(itemsAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(position == 0) {
Intent intent = new Intent(ktmList.this, dukeSmall.class);
startActivity(intent);
}else if (position == 8){
Intent intent = new Intent(ktmList.this, smc.class);
startActivity(intent);
}
}
});
}
}
and then I have a model class for each model with its specification, an example for a model is:
package com.example.ofir.myapplication.models;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.ofir.myapplication.R;
/**
* Created by Ofir on 23-Mar-17.
*/
public class smc extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.info_page);
int cc = 690;
int weight = 150;
int hp = 67;
int topspeed = 180;
ImageView logo = (ImageView) findViewById(R.id.logo_image);
logo.setImageResource(R.drawable.smc);
TextView Displacement = (TextView) findViewById(R.id.displacement_text);
Displacement.setText(cc + "cc");
TextView HP = (TextView) findViewById(R.id.hp_text);
HP.setText(""+hp);
TextView Weight = (TextView) findViewById(R.id.weight_text);
Weight.setText(""+weight);
TextView topSpeed = (TextView) findViewById(R.id.top_speed_text);
topSpeed.setText(topspeed + " km/h");
}
}
now my questions is, is there an easier way to achieve that? instead of setting a class for each and each model and settings tons of intents?
So for all items, you got common elements (Displacement, weight, topSpeed, etc.). You can make use of the Bundle class.
It's really easy.
Make a instance of a bundle
Bundle bundle = new Bundle();
Then on the bundle, just put whatever items that you like. For example if you want to put a arraylist,
bundle.putIntArray(arrayKey, int[]);
Note: key is there so that the next activity can recognize which item you want in the bundle.
Naturally, put the bundle on your intent.
intent.putExtra(bundleKey, bundle);
In your next activity, get intent, then your bundle.
Bundle bundle = getIntent().getExtras().getBundle(bundleKey);
Extract your arraylist from the bundle.
int yourArrayList[] = bundle.getIntArray(arrayKey);
And you're all done!
like putting ALL of the data in one class and just pull it from it?
I'd suggest that you make one Bike.java file that holds all information about a single Bike type (speed, image, CC, weight).
Then, you can have Bike smc = new Bike(690, 150, 67, 180, R.drawable.smc).
And you can load that into only one BikeDetailActivity.java using Intents.
And make a BikeAdapter.java that's an ArrayAdapter<Bike> so that when you click on any item, you just make an Intent and pass on the necessary information to display there.
You'll also need to learn to use getIntent to get the data.
Note: a database will be useful if you want to edit and save your bike information.

How to populate Contacts from Phone to Custom Listview?

I created a Custom ListView using BaseAdapter now I want to populate this Listview with Contact Name and Number from Phone book..I am trying this..
import java.util.ArrayList;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class Rabtaye extends Activity {
ListView msgList;
ArrayList<MessageDetails> details;
AdapterView.AdapterContextMenuInfo info;
Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main);
msgList = (ListView) findViewById(R.id.MessageList);
details = new ArrayList<MessageDetails>();
MessageDetails Detail = new MessageDetails();
cursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, null);
startManagingCursor(cursor);
String info[] = { ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone._ID };
for(String a:info){
Detail.setName(a);
}
Detail.setNumber("0313");
details.add(Detail);
// int to[] = { R.id.name, R.id.number };
// ListAdapter cursada = new SimpleCursorAdapter(this,
// android.R.layout.simple_expandable_list_item_2, cursor, info,
// to);
msgList.setAdapter(new CustomAdapter(details, this));
msgList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
TextView s = (TextView) arg1.findViewById(R.id.name);
String abc = s.getText().toString();
Toast.makeText(Rabtaye.this, abc, Toast.LENGTH_LONG).show();
}
});
}
}
I used different ways, but I am not able to populate ListView with Contact Name or Number. In this code I have to statically add name and number...I am quite confuse here..little help would be greatly appreciated. Thanks in Advance. I am newbie so please go easy on me..:)
Hmmm. You're on the right track, but I think you're wandering a bit.
A ListView is a view object, not a BaseAdapter. As far as I can tell from your code, you don't need a custom adapter for your ListView.
What you should do is bind a regular CursorAdapter to your ListView, load the Contacts data you want from the Contacts Provider using a CursorLoader, then move the resulting Cursor to the CursorAdapter.
You can find the instructions for doing this in this Android training class:
Loading Data in the Background.
What do you want in your custom ListView that you can't get from ListView itself?
If you're putting more than just a single list of items into a ListView (it looks like you're doing name, number, etc.) you have to create your own custom adapter. Extend the BaseAdapter class either in your activity, or in a new class. Then you'll have to override the getView() method. This is what is called every time a new item gets inflated.
You pass your ArrayList into the BaseAdapter when you create it. The getView() method of the adapter is where you code your logic to take the data and present it as a list item. You'll have to define a new XML file as a layout for each list item that contains your TextViews and whatnot for your different children in each list item, and that's what you populate with your data.
There are a bunch of examples all over if you search for "baseadapter". Here's one that gives a pretty good intro.

adding delete button to listview in android

i have a list view and i want to mimic the functionality of
UITableViewEditingStyle in iphone .
I want the listview to have a delete button and when the user clicks the deleting button, that particular row should get deleted not only from the database but also from the listview.
I am using ListActivity.
Thank you for your help.
Here is the code that i am using
import android.R.anim;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
public class EditSiteList extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.editsitelist);
HandleDatabase db = new HandleDatabase(null,null,null);
String names[] = db.getSites();
ListAdapter la = new Arraydapter(this,R.layout.editsiterow,R.id.sitename,names);
HandleDatabase hd = new HandleDatabase(null, null, null);
hd.getSitesCursor(), new String[]{"name"}, android.R.id.);
setListAdapter(la);
}
You have to implement your own ListAdapter with this functionality plus you have to decide where to situate the Delete button. At least I did so in my project when I had found that Android has no equivalents of this iPhone feature. In your ListAdapter you should delete the items from the ListView and from the DB manually.

Categories

Resources