I am trying to populate a ListView from a .txt file but somehow fail to it.
The file read and is added to the ArrayList properly. I have tried the ArrayAdapter to the ArrayList and set it as the Adapter of the ListView under OnCreate() and call notifyDataSetChanged() after the list is updated.
I'm fairly new to java, I'm more used to (and prefer) C#
Here's parts of my code:
public class MainActivity extends ActionBarActivity{
ArrayAdapter<String> arrayAdapter = null;
ArrayList<String> arrayList = null;
ListView listView = null;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
listView = (ListView) findViewById(R.id.lv_Run);
arrayList = new ArrayList<String>();
arrayList.clear();
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList);
listView.setAdapter(arrayAdapter);
}
//<...>
if (file.isFile() && file.getName().endsWith(".txt")){
Button btn = new Button(ll1.getContext());
btn.setText(file.getName().replace(".txt", ""));
btn.setTag(file.getName().replace(".txt", ""));
btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
String btnString = v.getTag().toString();
UpdateList(btnString);
}
});
btn.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
ll1.addView(btn);
}
//<...>
public void UpdateList(String btnString){
try{
File file = new File(runs.getAbsolutePath()+ File.separator + btnString + ".txt");
arrayList = getFileContent(file.getAbsolutePath());
arrayAdapter.notifyDataSetChanged();
catch (IOException e){
e.printStackTrace();
}
}
//<...>
public static ArrayList<String> getFileContent(String fileName) throws IOException{
ArrayList<String> result = new ArrayList<>();
File aFile = new File(fileName);
BufferedReader reader;
String aLine;
if (!aFile.isFile()){
return result;
}
try{
reader = new BufferedReader(new FileReader(aFile));
}
catch (FileNotFoundException e1){
e1.printStackTrace();
return result;
}
while ((aLine = reader.readLine()) != null){
result.add(aLine + "\n");
}
reader.close();
return result;
}
//<...>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:background="#ff000000"
android:baselineAligned="false"
android:id="#+id/pan_MasterPan">
<LinearLayout android:orientation="vertical"
android:layout_weight="2.5"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="#+id/pan_Left">
<LinearLayout android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="top"
android:layout_weight="8"
android:id="#+id/pan_SelRun">
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/select_run"
android:id="#+id/btn_LoadRun"
android:clickable="true"
android:onClick="runSelectClick"/>
</LinearLayout>
<LinearLayout android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="bottom"
android:layout_weight="1"
android:focusableInTouchMode="false"
android:id="#+id/pan_RunPOI">
<ListView
android:id="#+id/lv_Run"
android:layout_width="match_parent"
android:layout_height="0dp"
android:visibility="visible"
android:layout_weight="1"
android:dividerHeight="1dp"
android:drawSelectorOnTop="true"
android:clickable="true"
android:choiceMode="singleChoice"
android:divider="#android:color/black"/>
</LinearLayout>
</LinearLayout>
<LinearLayout android:orientation="vertical"
android:layout_weight="1"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:background="#ff1A1A1A"
android:id="#+id/pan_Right">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ForDebug"
android:text="#string/debugbtnstrg"
android:clickable="true"
android:onClick="ForDebug_OnClick"
android:longClickable="false"
android:textStyle="italic"/>
</LinearLayout>
</LinearLayout>
Two days I try this and that without any difference between every try...
Thanks a lot for you time, it's really appreciated.
---- Edit ----
Updated Code: (sorry to show only parts, this is part of a massive and messy code...)
public void UpdateList(String btnString){
try{
File file = new File(runs.getAbsolutePath()+ File.separator + btnString + ".txt");
arrayList = getFileContent(file.getAbsolutePath());
Toast.makeText(getApplicationContext(), "aL_Size: " + arrayList.size(), Toast.LENGTH_LONG).show();
//return 5
arrayAdapter.addAll(arrayList);
Toast.makeText(getApplicationContext(), "aA_Count: " + arrayAdapter.getCount(), Toast.LENGTH_LONG).show();
//return 5
arrayAdapter.notifyDataSetChanged();
catch (IOException e){
e.printStackTrace();
}
}
---- Edit 2 ----
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
listView = (ListView) findViewById(R.id.lv_Run);
arrayList = new ArrayList<String>();
arrayList.clear();
arrayList.add("TEST1");
arrayList.add("TEST2");
arrayList.add("TEST3");
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList);
listView.setAdapter(arrayAdapter);
}
Call ArrayAdapter.addAll method for adding new items in current adapter of ListView before calling notifyDataSetChanged :
arrayList = getFileContent(file.getAbsolutePath());
arrayAdapter.addAll(arrayList);
arrayAdapter.notifyDataSetChanged();
Related
I'm making simple listview of therapies and the list is not showing on the emulator. I've upgraded and downgraded my api from 22 to 30 and change relative layout to linear layout but still the list is not showing.
activty_stress.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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"
android:weightSum="9"
android:background="#83BCD4"
tools:context=".stress">
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Find your relaxation"
android:textColor="#color/white"
android:textSize="18pt" />
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="70dp"/>
</RelativeLayout>
stress.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stress);
ListView listView = findViewById(R.id.listview);
List<String> list = new ArrayList<>();
list.add("Therapy1");
list.add("Therapy2");
list.add("Therapy3");
list.add("Therapy4");
list.add("Therapy5");
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1,list);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position==0){
//clicked therapy1
startActivity(new Intent(stress.this,Therapy1.class));
} else if (position==1){
//clicked therapy2
}else{
}
}
});
}
Heyy try replacing your RelativeLayout with LinearLayout, or remove weightSum because weightSum cannot be used with RelativeLayout
Replace with this code.
Note: Whenever you give textSize, give it in sp not in Pixel.
activty_stress.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:background="#83BCD4"
android:orientation="vertical">
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Find your relaxation"
android:textColor="#color/white"
android:textSize="30sp" />
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="70dp" />
</RelativeLayout>
stress.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = findViewById(R.id.listview);
List<String> list = new ArrayList<>();
list.add("Therapy1");
list.add("Therapy2");
list.add("Therapy3");
list.add("Therapy4");
list.add("Therapy5");
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) {
//clicked therapy1
// startActivity(new Intent(stress.this,Therapy1.class));
} else if (position == 1) {
//clicked therapy2
} else {
}
}
});
}
Output:
I am trying to make an activity that provides a list of emergency phone numbers with the ability for the user to add their own custom entries and save them. For some reason, the ListView doesn't appear on the activity. I'm pretty sure I'm doing something wrong in the CustomAdapter class that I made to hold two text boxes in each segment of the ListView.
I'm also trying to set the listView to start a phone activity with the phone number of whatever segment was touched, and I'm unsure if I'm doing this correctly.
PhoneList.java :
public class PhoneList extends AppCompatActivity {
ArrayList<String> customList;
ArrayList<String> numList;
Bundle b;
TinyDB tinydb;
CustomAdapter dataAdapter;
ListView phoneListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_list);
phoneListView = (ListView)findViewById(R.id.listViewPhone);
Integer num = null;
String label = "";
customList = null;
numList = null;
tinydb = new TinyDB(this);
Button saveContact = (Button)(findViewById(R.id.button4));
b = new Bundle();
customList = tinydb.getListString("label");
ArrayList<Integer> temp = tinydb.getListInt("num");
for(int i = 0; i < temp.size(); i++){
numList.add(temp.get(i).toString());
}
saveContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText enteredLabel = (EditText)findViewById(R.id.editText2);
EditText enteredNum = (EditText)findViewById(R.id.editText);
String label = enteredLabel.getText().toString();
Integer num = Integer.parseInt(enteredNum.getText().toString());
b.putString("label",label);
b.putInt("num",num);
addPhoneItem();
}
});
ArrayList<String> phoneList = new ArrayList<>();
phoneList.add("Emergencies");
phoneList.add("Travel Info ");
phoneList.add("Poison Control ");
phoneList.add("AAA: 1(800)836-2582");
if(customList != null && customList.size() > 0) phoneList.addAll(customList);
ArrayList<String> numberList = new ArrayList<>();
numberList.add("911");
numberList.add("511");
numberList.add("18002221222");
numberList.add("18008362582");
if(numList != null && numList.size()>0) {
for (int i = 0; i < numList.size(); i++) {
numberList.add(numList.get(i).toString());
}
}
dataAdapter = new CustomAdapter(this,numberList,phoneList);
phoneListView.setAdapter(dataAdapter);
}
public void addPhoneItem(){
customList.add(b.getString("label"));
numList.add(b.getString("num"));
tinydb.putListString("label",customList);
tinydb.putListString("num",numList);
dataAdapter = new CustomAdapter(this,numList,customList);
phoneListView.setAdapter(dataAdapter);
}
private class CustomAdapter extends ArrayAdapter<String> {
ArrayList<String> labels;
ArrayList<String> nums;
Context context;
public CustomAdapter(Context context, ArrayList<String> n,ArrayList<String> l) {
super(context,R.layout.phone_item);
this.context = context;
labels = new ArrayList<String>();
labels.addAll(l);
nums = new ArrayList<String>();
nums.addAll(n);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
try {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.phone_item, null);
holder = new ViewHolder();
holder.viewLabel = (TextView) convertView.findViewById(R.id.editText);
holder.viewNumber = (TextView) convertView.findViewById(R.id.editText2);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
String label = labels.get(position);
String num = nums.get(position);
holder.viewLabel.setText(label);
holder.viewNumber.setText(num);
holder.viewNumber.setTag(num);
holder.viewNumber.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String str = "tel:" + (EditText) v.getTag();
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(str));
try {
startActivity(intent);
} catch (Exception e) {
Toast.makeText(getContext(),"Exception Caught in CustomAdapter",Toast.LENGTH_SHORT).show();
}
}
});
}
catch(Exception e){
Toast.makeText(getContext(),"Exception caught",Toast.LENGTH_SHORT).show();
}
return convertView;
}
}
private class ViewHolder{
TextView viewLabel;
TextView viewNumber;
}
}
activity_phone_list.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res``/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.rvtripapp.dempsey.rvtripapp.PhoneList">
<ListView
android:layout_width="wrap_content"
android:layout_height="400dp"
android:id="#+id/listViewPhone"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:editable="true"
android:hint="Label" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/editText2"
android:layout_below="#+id/editText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="Phone Number" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+"
android:id="#+id/button4"
android:textSize="40dp"
android:background="#44fe66"
android:layout_alignBottom="#+id/editText2"
android:layout_alignRight="#+id/listView"
android:layout_alignEnd="#+id/listView" />
</RelativeLayout>
phone_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView3" />
</LinearLayout>
Any help is much appreciated, thank you.
Change the super keyword line to
super(context,R.layout.phone_item, n);
Have you tried to override the getCount method of the CustomAdapter class ?
#Override
public int getCount() {
return labels.size();
}
You are setting your custom adapter outside onCreate() try to set it inside the onCreate().
I want to add two buttons in each row of a listview. While using only one Activity means that in my code i have one MainActivity.java and its layout (activity_main.xml) and an additional layout (list_item.xml) which have items in each row (Textviews) but when i add two buttons in a list_item.xml and initialize in MainActivity and add listners on it it shows me an exception which is shared below.Help me to solve my problem, Any sort of help will be highly appreciated.
MainActivity.java
public class MainActivity extends ActionBarActivity
{
String myJSON ;
String id;
private static final String TAG_RESULTS="result";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_ADD ="address";
JSONArray peoples = null;
ArrayList <HashMap <String, String> > personList;
ListView list;
TextView quant;
int count=0;
Button b_plus,b_minus;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.listView);
personList = new ArrayList<HashMap<String,String>>();
quant=(TextView)findViewById(R.id.quantity);
b_plus=(Button)findViewById(R.id.ib_plus);
b_minus=(Button)findViewById(R.id.ib_minus);
b_plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
count++;
quant.setText(Integer.toString(count));
}
});
b_minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
count--;
quant.setText(Integer.toString(count));
}
});
getData();
}
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String address = c.getString(TAG_ADD);
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_ID,id);
persons.put(TAG_NAME,name);
persons.put(TAG_ADD,address);
personList.add(persons);
}
final ListAdapter adapter = new SimpleAdapter
(
MainActivity.this, personList, R.layout.list_item,
new String[]{TAG_ID,TAG_NAME,TAG_ADD},
new int[]{R.id.id, R.id.name, R.id.address}
);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
switch(i)
{
case 0 :
Intent appInfo = new Intent(MainActivity.this, MainActivity2.class);
startActivity(appInfo);
break;
case 1 :
Intent ap = new Intent(MainActivity.this, MainActivity3.class);
startActivity(ap);
break;
case 2 :
Intent Info = new Intent(MainActivity.this, MainActivity2.class);
startActivity(Info);
break;
}}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://10.0.2.2/in.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
} }
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
android:background="#ff3c3f41"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<ListView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/listView"
/>
</LinearLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" >
<TextView
android:id="#+id/id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:textColor="#fff9f9f9"
android:textStyle="bold" />
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="#fff9f9f9"
android:textStyle="bold"/>
<TextView
android:id="#+id/address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:textColor="#fff9f9f9"
android:textStyle="bold" />
<TextView
android:id="#+id/quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:textColor="#fff9f9f9"
android:textStyle="bold" />
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="166dp"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" >
<ImageButton
android:layout_width="58dp"
android:layout_height="52dp"
android:src="#drawable/plus"
android:layout_gravity="start"
android:id="#+id/ib_plus" />
<ImageButton
android:layout_width="58dp"
android:layout_height="52dp"
android:src="#drawable/minus"
android:id="#+id/ib_minus"
android:layout_gravity="center_horizontal"
android:layout_alignBottom="#+id/ib_plus"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignTop="#+id/ib_plus" />
</RelativeLayout>
logcat:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.abdul.zx.MainActivity.onCreate(MainActivity.java:62)
You'll have to make your adapter more complicated, because there is not one but many buttons and text fields. Pseudo code like solution below. Replace the line where you create your adapter with something like this:
final ListAdapter adapter = new SimpleAdapter
(MainActivity.this, personList, R.layout.list_item,
new String[]{TAG_ID,TAG_NAME,TAG_ADD},
new int[]{R.id.id, R.id.name, R.id.address}) {
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
final TextView quant=(TextView)view.findViewById(R.id.quantity);
final ImageButton b_plus=(ImageButton)view.findViewById(R.id.ib_plus);
final ImageButton b_minus=(ImageButton)view.findViewById(R.id.ib_minus);
b_plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
count++;
quant.setText(Integer.toString(count));
}
});
b_minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
count--;
quant.setText(Integer.toString(count));
}
});
return view;
}
};
Remove everything related to quant, b_minus, b_plus from other places in your activity
You need to inflate the list_item layout first as a view. Then, you need to initialize your ImageButtons by view.findViewById(). Now, you are trying to use the ImageButton's of a layout other than what you have set in onCreate. Or another approach would be to set onClick methods inside the adapter.
The problem is that list_item.xml is inflated for each row of data in your ListView. At the point in onCreate() where you try to get the button views, they have not yet been created. In order to set listeners to each button, you need to create a custom adapter class. You will then set the listeners in the getView() method.
Your buttons are not defined in R.layout.activity_main so findViewById will return null since they are not there.
quant is also null, by the way, for the same reason.
You must define your buttons in your SimpleAdapter class because they are in the list_item.xml. (Assuming SimpleAdapter inflates list_item.xml)
I believe that you might be doing these steps in the wrong place:
quant=(TextView)findViewById(R.id.quantity);
b_plus=(Button)findViewById(R.id.ib_plus);
b_minus=(Button)findViewById(R.id.ib_minus);
I think what's happening is that the code is searching for them in activity_main.xml but because they're not there, they end up being null. Hence, the exception you're seeing.
Since the TextView and the Buttons are related to each ListView item, then that's where the initialization should go. I see you're using a SimpleAdaptor which I am not familiar with. But if you create your custom adaptor for ListView, then you can initialize the TextView and the Buttons in the getView() of the Adaptor kind of like this: Custom Adapter for List View.
You can set the button listeners there as well which will provide you with the position of the ListItem where a certain button was clicked.
I am facing an issue. i am trying to show sqlite data in the simple adapter but the data is not showing up in my application i don't know what is the wrong. i am new to android development need help.....
Here is my code
public class user extends AppCompatActivity {
sqlite_database database;
ListView listView;
ArrayList<HashMap<String, String>> arrayList;
String stname,stfname,contact;
HashMap<String, String> hmap;
String n,f,c;
TextView studentName, studentFatherName,studnetContact;
Button show;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
database = new sqlite_database(getApplicationContext());
listView=(ListView)findViewById(R.id.userlistView);
show = (Button)findViewById(R.id.btnShoww);
studentName = (TextView)findViewById(R.id.studentName);
studentFatherName = (TextView)findViewById(R.id.studentFName);
studnetContact = (TextView)findViewById(R.id.studentContact);
studentName.setText(n);
studentFatherName.setText(f);
studnetContact.setText(c);
ShowData();
arrayList = new ArrayList<HashMap<String,String>>();
try{
Cursor c = database.showAllStudentData();
while(c.moveToNext())
{
hmap= new HashMap<String, String>();
stname=c.getString(0);
hmap.put("n", stname);
stfname=c.getString(1);
hmap.put("f", stfname);
contact=c.getString(2);
hmap.put("c", contact);
arrayList.add(hmap);
}
}
catch(Exception e){
Log.e("error",e.getMessage());
}
String from[]={n,f,c};
int to[]={R.id.studentName,R.id.studentFName,R.id.studentContact};
SimpleAdapter adapter = new SimpleAdapter(this, arrayList, R.layout.user_info_layout, from, to);
listView.setAdapter(adapter);
}
public void ShowData()
{
show.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor result = database.showAllStudentData();
if (result.getCount() == 0) {
//show Message
showMessage("Error", "Nothing is here");
return;
}
StringBuffer buffer = new StringBuffer();
while (result.moveToNext()) {
buffer.append("Name: " + result.getString(0) + "\n");
buffer.append("Father Name: " + result.getString(1) + "\n");
buffer.append("Contact: " + result.getString(2) + "\n\n");
}
showMessage("Data", buffer.toString());
}
}
);
}
public void showMessage (String title, String message)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
}
And this is my SQLite code
public Cursor showAllData()
{
SQLiteDatabase mydatabase = helper.getWritableDatabase();
Cursor result = mydatabase.rawQuery("select * from "+ Helper.TABLE_NAME,null);
return result;
}
layout....
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/userImage" />
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="match_parent"></LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/studentName" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/studentFName" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/studentContact" />
</LinearLayout>
userActivity
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.ks.doit.user">
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#006700"
android:id="#+id/toolbar"></android.support.v7.widget.Toolbar>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/userlistView"
android:layout_below="#+id/toolbar"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show All Data"
android:id="#+id/btnShoww"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
You should use CursorAdapter iа you're querying data from database for example:
// columns
final String[] columns = new String[] { "stname", "stfname, "contact" };
// resource id's
final int[] to = new int[] { R.id.studentName, R.id.studentFName, R.id.studentContact };
// adapter
final SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.student_layout, cursor, columns, to);
// set adapter to listview
listView.setListAdapter(mAdapter);
I have fixed it! It created a list of empty strings named from[].
So, it should be like this:
String from[] = {"n", "f", "c"};
I'm trying to make an audio recorder for which I want to display a list of recordings done till now.
I'm able to get the list recorded files from my SD card in to an ArrayList, but my app crashes when it tries to populate the list view.
ListRecordings.java is called using an Intent from MainActivity.java.
Here is the for ListRecordings.java:
public class ListRecordings extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.listrecordings);
ListView lv;
String path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/MyAudioRecorder";
ArrayList<String> FilesInFolder = GetFiles(path);
lv = (ListView) findViewById(R.id.filelist);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.textlayout,
FilesInFolder);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
// Clicking on items
}
});
}
public ArrayList<String> GetFiles(String DirectoryPath) {
ArrayList<String> MyFiles = new ArrayList<String>();
File f = new File(DirectoryPath);
f.mkdirs();
File[] files = f.listFiles();
if (files.length == 0)
return null;
else {
for (int i = 0; i < files.length; i++)
MyFiles.add(files[i].getName());
}
return MyFiles;
}
}
Here's the code for listrecordings.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/filelist"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
Here's the code for textlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/label"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp"
android:textStyle="bold" >
</TextView>
Any help is appreciated.
I've just started with android so excuse me if i made any lame mistakes.
Thanks
You missing this line in onCreate()
super.onCreate(savedInstanceState);
Add something like this
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.textlayout,
R.id.textview_id_in_textlayout,FilesInFolder);
I hope this will help.