I am doing lazyloading to display images and text. I have got everything up and now, trying to add a textview in the view. However, my adapter is overlapping my view. Simpler terms is that, the listview is overlapping the textview. I'm not sure where I'm doing it wrong because the original example is able to display a button just below the listview but I'm not. I'm not getting any errors. My listview just covers the whole screen. Any idea what might be the problem?
main.java
public class main extends Activity {
private static final String targetURL ="http://www.google.com/images";
ListView list;
ProgressDialog dialog;
private String[] mStrings = {};
private String[] dStrings = {};
//TextView tv;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new TheTask().execute();
list=(ListView)findViewById(R.id.list);
TextView tv = (TextView)findViewById(R.id.tv);
//tv.setText("Text View is displayed");
}
protected class TheTask extends AsyncTask<Void, Void, MyResultClass >{
protected void onPreExecute() {
dialog = ProgressDialog.show(Cats.this, "Retrieving Information", "Please wait for few seconds...", true, false);
dialog.setCancelable(true);
}
protected MyResultClass doInBackground(Void... params) {
searchContent();
MyResultClass result = new MyResultClass();
result.mStrings = mStrings;
result.dStrings = dStrings;
return result;
}
protected void onPostExecute(MyResultClass result) {
dStrings = result.dStrings;
mStrings = result.mStrings;
LazyAdapter adapter = new LazyAdapter(Cats.this, mStrings, dStrings);
list.setAdapter(adapter);
dialog.dismiss();
}
}
class MyResultClass
{
public String[] mStrings;
public String[] dStrings;
}
public void searchContent()
{
String imageC = "";
String textC = "";
try {
URL url = new URL(targetURL);
// Make the connection
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line = reader.readLine();
Pattern sChar = Pattern.compile("&.*?;");
line.replaceAll("\\<.*?\\>", "");
Matcher msChar = sChar.matcher(line);
while (msChar.find()) line = msChar.replaceAll("");
while (line != null) {
if(line.contains("../../"))
{
int startIndex = line.indexOf("../../") + 6;
int endIndex = line.indexOf(">", startIndex + 1);
String abc = "http://www.google.com/";
String imageSrc = line.substring(startIndex,endIndex);
//complete full url
String xyz = abc +imageSrc;
xyz = xyz.substring(0,xyz.indexOf('"'));
xyz = xyz +";";
xyz = xyz.replaceAll(" ", "%20");
imageC += xyz;
mStrings = imageC.split(";");
line = reader.readLine();
}
if(line.contains("../../") == false)
{
line = reader.readLine();
}
if (line.contains("Gnametag"))
{
int startIndex = line.indexOf("Gnametag") + 10;
int endIndex = line.indexOf("<", startIndex + 1);
String gname = line.substring(startIndex,endIndex);
textC = textC.replaceAll("</span>", "");
textC += "Name: "+gname+ "\n";
}
if (line.contains("Age"))
{
textC += "Age: "+reader.readLine() + "\n" + ";";
textC = textC.replaceAll(" ", "");
dStrings = textC.split(";");
}
if (line.contains("Last Update"))
{
reader.close();
}
}
// Close the reader
reader.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Adapter.java
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if(convertView==null){
vi = inflater.inflate(R.layout.item, null);
holder=new ViewHolder();
holder.text=(TextView)vi.findViewById(R.id.text);;
holder.image=(ImageView)vi.findViewById(R.id.image);
vi.setTag(holder);
}
else
holder=(ViewHolder)vi.getTag();
holder.text.setText(text[position]);
holder.image.setTag(data[position]);
imageLoader.DisplayImage(data[position], activity, holder.image);
return vi;
}
item.xml (used by Adapter.java)
<?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:background="#FFFFFF">
<ImageView
android:id="#+id/image"
android:layout_width="90dip"
android:layout_height="90dip"
android:src="#drawable/stub"
android:scaleType="centerCrop"
android:layout_gravity="left|center_vertical"
/>
<TextView
android:id="#+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="15dip"/>
</LinearLayout>
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFFFF">
<LinearLayout
android:id="#+id/linear1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#FFFFFF">
<TextView
android:id="#+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Testing 123"
/>
</LinearLayout>
<LinearLayout
android:id="#+id/linear2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/linear1"
android:background="#FFFFFF">
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="30dp"/>
</LinearLayout>
</RelativeLayout>
Just remove the + symbol from this line
android:layout_below="#+id/linear1"
in second linear layout stanza.
When you say the ListView covers the whole screen, do you refer to the result on an actual phone or e.g. the preview in Eclipse? If it shows up correctly in the latter, then likely the issue is somewhere in your Java code.
Anyways, I don't seem to be able to reproduce your problem on either one. However, there are two things I would try:
First, change the order of calls in the onCreate() method of your Activity. Specifically, don't execute your AsyncTask until after you've initialized the ListView, since you're using it in the onPostExecute(). Although this probably won't make a difference, you'd better avoid any chances on a race condition.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list=(ListView)findViewById(R.id.list);
TextView tv = (TextView)findViewById(R.id.tv);
// start task after 'list' is initialized.
new TheTask().execute();
}
Secondly, the layout file containing your ListView is unnecessarily complicated. Preferably you want to keep layouts as simple as possible and limit the nesting for a more flat hierarchy. You could simply get rid of the absolete LinearLayouts, and, if you prefer working with them, change the parent to one. Also, android:orientation="vertical" is not a valid attribute for a RelativeLayout, so make sure you remove that.
Same RelativeLayout, but without the LinearLayouts:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFFFF" >
<TextView
android:id="#+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Testing 123" />
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tv"
android:layout_marginBottom="30dp" />
</RelativeLayout>
Same behaviour, but with a LinearLayout as root element:
<?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="fill_parent"
android:background="#FFFFFF"
android:orientation="vertical" >
<TextView
android:id="#+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Testing 123" />
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_marginBottom="30dp" />
</LinearLayout>
Add android:layout_alignParentTop="true" to your top LinearLayout (linear1)
<LinearLayout
android:id="#+id/main_xml_linearlayout_one"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
>
<TextView
android:id="#+id/main_xml_textview_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
<LinearLayout
android:id="#+id/main_xml_linearlayout_two"
android:layout_below="#id/main_xml_linearlayout_one"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#FFFFFF" >
<ListView
android:id="#+id/main_xml_listview_list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="30dp"/>
</LinearLayout>
Related
I'm kinda new to android studio and most of my work was done referring to Stack Overflow answered questions and topics cutting short to the question.
my JSON is as such:
[
{ "name":"station1",
"url":"http://example1.com",
"image":"R.drawable.radio1"
},
{ "name":"station2",
"url":"example2.com",
"image":"R.drawable.radio2"
}
]
and so on,
and my XML is
<HorizontalScrollView
android:id="#+id/horizontalScrollView1"
android:layout_width="fill_parent"
android:layout_height="100dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
tools:layout_editor_absoluteY="0dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<RelativeLayout
android:id="#+id/relative1"
android:layout_width="100dp"
android:layout_height="100dp"></RelativeLayout>
</LinearLayout>
</HorizontalScrollView>
I need to load the image and name in a scroll view horizontally created dynamically every time I add another "name and image" to the JSON file please can someone help me with a code (the text below every image that loads).
First i suggest to create a class BEAN like this:
public class MyBean{
String name;
String url;
String image;
}
Now, as GrIsHu describes in their answer here:
you need to read the Json File from your assests file using below code:
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getActivity().getAssets().open("yourfilename.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
After, transform the Json String into JsonArray like this:
JSONArray ja = new JSONArray(loadJSONFromAsset());
Now you can popolate a
List<MyBeen.class> lst
like this:
for (int i = 0; i < ja.length(); i++) {
lst.add(gSon.fromJson(ja.get(i).toString(), MyBeen.class));
}
first to all do you need to change HorizontalScrollView in ListView
https://developer.android.com/guide/topics/ui/layout/listview.html
, as:
<LinearLayout
android:id="#+id/fullscreen_content_controls"
style="?metaButtonBarStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:ignore="UselessParent">
<ListView
android:id="#+id/lstView"
android:layout_margin="5dp"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:divider="#android:color/transparent"
android:dividerHeight="10.0sp">
</ListView>
</LinearLayout>
When you add a in MainClass this code for work with ListView:
ListView listView = findViewById(R.id.lstView);
listView.setAdapter(new CustomAdapter(this, lst));
After, in CustomAdapter.java, need:
public class CustomAdapter extends BaseAdapter {
public CustomAdapter(MainClass mainActivity, List<?> iLst) {
lst = iLst;
context=mainActivity;
inflater = ( LayoutInflater )context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View rowView;
rowView = inflater.inflate(R.layout.listview_custom, null); <-- RAPPRESENTE A SINGLE ROW LAYOUT
ImageView img = (ImageView) rowView.findViewById(R.id.customImg);
TextView text =(TextView) rowView.findViewById(R.id.customText);
return rowView;
}
}
At end, you add the XML layout for a single row, it will duplicate automatically for each row:
<?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:background="#drawable/border_radius"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="1"
android:orientation="horizontal">
<LinearLayout
android:layout_width="0sp"
android:layout_weight=".2"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center">
<ImageView
android:id="#+id/customImg"
android:layout_width="50sp"
android:layout_height="45sp"
android:drawableTint="#color/White"
android:background="#drawable/upload"
android:tint="#color/White"/>
</LinearLayout>
<LinearLayout
android:layout_width="0sp"
android:layout_weight=".6"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/customText"
android:paddingTop="5dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20dp"
android:ellipsize="none"
android:scrollHorizontally="false"
android:maxLines="100"
android:textColor="#color/White"
android:text="Title" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
How to get value from dynamically created EditText in Android?
This is my dynamic view (XML file)
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="#+id/et_waypoint"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#drawable/background"
android:hint="Way Points"
android:padding="10dp"
android:textSize="16sp" />
<Button
android:id="#+id/btn_waypoint"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Find" />
</LinearLayout>
And I am using LayoutInflater because I want perfect Designed layout which is not accomplish by me via setLayoutParams so this is the reason I am using LayoutInflater.
And here is my code:
LayoutInflater l = getLayoutInflater();
final LinearLayout mainActivity = (LinearLayout) findViewById(R.id.dynamic);
final View view = l.inflate(R.layout.dynamic_layout_waypoints, null);
buttonWayPoints = (Button) view.findViewById(R.id.btn_waypoint);
editTextWayPoints = (EditText) view.findViewById(R.id.et_waypoint);
mainActivity.addView(editTextWayPoints);
I am new to Android. Most of people suggest this solution but it's not worked for me, the issue is when I implement this code my ADD NEW EDIT TEXT BUTTON not respond me.
This is how I am trying to get inserted value but it returns value of only last created edit text:
public Cursor getPerson(String Query) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(Query, null);
return c;
}
sb is StringBuilder sb;, w is String w;
String queryWayPoints = "select * from route_table where trip_id = " + t;
Cursor s = myDb.getPerson(queryWayPoints);
int count3 = s.getCount();
for (int j = 0; j < count3; j++) {
s.moveToNext();
w = s.getString(s.getColumnIndex("waypoints"));
// se.append(w + "." + "00");
}
trip_name.setText(n);
trip_date.setText(d);
sb.append(w);
}
trip_route.setText(sb.toString());
Although, I didn't get what exactly your question is, still I'll try to help.
What exactly this code does is, on clicking the button on top an new layout(one that you wanted) will add to the activity screen at runtime, i.e an edittext with a button, and when you click on that button, A toast with the value of respective edittext will be shown. Hence solving the problem of getting the value of dynamically added edittext
MainActivity
public class MainActivity extends AppCompatActivity {
Button generateET;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final LinearLayout myLinearLay = (LinearLayout) findViewById(R.id.dynamic);
generateET = (Button) findViewById(R.id.generateBtn);
generateET.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LayoutInflater l = getLayoutInflater();
final View viewToAdd = l.inflate(R.layout.to_add, null);
Button buttonWayPoints = (Button) viewToAdd.findViewById(R.id.btn_waypoint);
final EditText editTextWayPoints = (EditText) viewToAdd.findViewById(R.id.et_waypoint);
buttonWayPoints.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (editTextWayPoints.getText().toString() != null) {
Toast.makeText(MainActivity.this, editTextWayPoints.getText().toString(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "No text found", Toast.LENGTH_SHORT).show();
}
}
});
myLinearLay.addView(viewToAdd);
}
});
}
}
activity_main.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"
tools:context="com.techmahindra.stackques.MainActivity">
<Button
android:id="#+id/generateBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="add editText To layout" />
<ScrollView
android:layout_below="#+id/generateBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fillViewport="true">
<LinearLayout
android:id="#+id/dynamic"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
></LinearLayout>
</ScrollView>
</RelativeLayout>
to_add.xml(layout which will be inflated at runtime)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="#+id/et_waypoint"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="Way Points"
android:padding="10dp"
android:textSize="16sp" />
<Button
android:id="#+id/btn_waypoint"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Find" />
</LinearLayout>
There are some problems with your code. You're trying to add editTextWayPoints to mainActivity, but editTextWayPoints already has a parent, which is view. I think you should be adding view to mainActivity (mainActivity.addView(view)). Finally, to access the value of editTextWayPoints, you simply do editTextWayPoints.getText().toString();
I want some help with putting data from multiple text files into one table shown on an activity.
The text file has a value on each line.
I want these strings to be shown on one column, in a table, where each column shows another text files data of similar format.
I want something like this to be shown:
The code im currently using shows one text file in a textview, how can i manipulate the code to make what i need possible?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stats);
File sdCard = Environment.getExternalStorageDirectory();
String path = sdCard.getAbsolutePath() + "/SO/";
File file = new File(path + "cheststats.txt");
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
}
TextView tv = (TextView)findViewById(R.id.tv);
tv.setText(text);
}
}
This is not a good question, because all trivial information that you need for doing this are on Android Developers. But anyway, I hope following steps help you:
1) Create stats.xml layout for stats table:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tableStats"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Stats"
android:gravity="center"
android:id="#+id/textView4" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Text File 1 Data"
android:id="#+id/textView1" />
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Text File 2 Data"
android:id="#+id/textView2" />
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Text File 3 Data"
android:id="#+id/textView3" />
</TableRow>
</TableLayout>
2) Create stats_row.xml layout for stats table rows:
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/textView1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_vertical|end" />
<TextView
android:id="#+id/textView2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_vertical|end" />
<TextView
android:id="#+id/textView3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_vertical|end" />
</TableRow>
3) Next, create function for reading file:
private List<String> readFileData(String filePath) {
List<String> values = new ArrayList<>();
try {
BufferedReader fileBufferedReader = new BufferedReader(new FileReader(new File(filePath)));
String value;
while ((value = fileBufferedReader.readLine()) != null) {
values.add(value);
}
fileBufferedReader.close();
} catch (IOException ignore) {
}
return values;
}
4) Create function for filling stats row view:
private void fillView(View view, String dataset1Value, String dataset2Value, String dataset3Value) {
TextView textView1 = (TextView) view.findViewById(R.id.textView1);
TextView textView2 = (TextView) view.findViewById(R.id.textView2);
TextView textView3 = (TextView) view.findViewById(R.id.textView3);
textView1.setText(dataset1Value);
textView2.setText(dataset2Value);
textView3.setText(dataset3Value);
}
5) Finally your onCreate function should be like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stats);
TableLayout tableStats = (TableLayout) findViewById(R.id.tableStats);
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/SO/";
List<String> data1 = readFileData(path + "file1.txt");
List<String> data2 = readFileData(path + "file2.txt");
List<String> data3 = readFileData(path + "file3.txt");
int maxDataSetSize = Math.max(data1.size(), Math.max(data2.size(), data3.size()));
for (int i = 0; i < maxDataSetSize; i++) {
String dataset1Value = data1.size() > i ? data1.get(i) : null;
String dataset2Value = data2.size() > i ? data2.get(i) : null;
String dataset3Value = data3.size() > i ? data3.get(i) : null;
View statsRowview = getLayoutInflater().inflate(R.layout.stats_row, null);
fillView(statsRowview, dataset1Value, dataset2Value, dataset3Value);
tableStats.addView(statsRowview);
}
}
I'm not sure that it will work at the first attempt. I have not tested.
My question: Why am I getting an error of java.lang.NullPointerException for trying to set set an adapter to one of my listviews in subListView.setAdapter(adapter2);
I am trying to create an app for learning purposes that will display subjects in a listview and when one of the items/subjects on the listview is clicked a sub item list will appear.
Right now I am just trying to show a listview view with their subitems shown.
Here is my code:
activity_main.xml
<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=".MainActivity" >
<TextView
android:id="#+id/textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minHeight="150dp"
android:layout_alignLeft="#+id/button1"
android:layout_alignRight="#+id/listView1"
android:layout_below="#+id/button1"
android:text="#string/hello_world" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textview1" >
</ListView>
</RelativeLayout>
group_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/groupItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ListView
android:id="#+id/sublistView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/groupItem"
android:layout_marginLeft="26dp" >
</ListView>
</RelativeLayout>
db_items.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:adjustViewBounds="true"
android:maxHeight="60dp"
android:maxWidth="60dp"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/subSubjectTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView1"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/imageView1"
android:text="Jesus is God"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/subIdtextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Small Text"
android:visibility="invisible"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/subScriptTextView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/textView1"
android:text="John 1:1-12"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RelativeLayout>
MainActivity.java
public class MainActivity extends Activity {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
protected void onCreate(Bundle savedInstanceState) {
//Creates DB and Tables if they do not exist... This part works
popList();
}
public void popList(){
ListView listView = (ListView) findViewById(R.id.listView1);
ListView subListView = (ListView) findViewById(R.id.sublistView);
TextView textv = (TextView)findViewById(R.id.textview1);
String topList[] = {"First", "Second", "Third"};
//Queries the DB and stores it in a Cursor... This part works
textv.append(" Cursor Count = " + c.getCount()); //this is for debugging purposes
int iId = c.getColumnIndex("id");
int iSummary = c.getColumnIndex("Summary");
int iScripts = c.getColumnIndex("Scripts");
int iDescription = c.getColumnIndex("Description");
int iSourceType = c.getColumnIndex("SourceType");
cursor.moveToFirst();
for (int j=0; j<c.getCount(); j++)
{
int image = 0;
if(c.getString(iSourceType).equals("Bible"))
{
image = R.drawable.bible;
}
if(c.getString(iSourceType).equals("Article"))
{
image = R.drawable.article;
}
if(c.getString(iSourceType).equals("Video"))
{
image = R.drawable.video;
}
myLVItems.add(new lvItem(c.getString(iId), c.getString(iSummary), c.getString(iScripts), c.getString(iDescription), image));
c.moveToNext();
}
ArrayAdapter<lvItem> adapter2 = new myListAdapter();
textv.append(" subListView Count = " + myLVItems.size()+ " adapter2 Count: " + adapter2.getCount()); //this is for debugging purposes
subListView.setAdapter(adapter2); //this is first error that the logcat points to
for (int i=0; i<topList.length; i++)
{
myGroupTopItems.add(new topgroupItem(topList[i], null));
}
ArrayAdapter<topgroupItem> adapter = new myTopListAdapter();
listView.setAdapter(adapter);
}
private class myListAdapter extends ArrayAdapter<lvItem>{
public myListAdapter(){
super(MainActivity.this, R.layout.db_items, myLVItems);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// make sure we have a view to work with (may have been given null
View itemView = convertView;
if(itemView == null)
{
itemView = getLayoutInflater().inflate(R.layout.db_items, parent, false);
}
//find the item to work with
lvItem currentLVItem = myLVItems.get(position);
//fill the view
ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView1);
imageView.setImageResource(currentLVItem.getIconId());
TextView hiddenView = (TextView) itemView.findViewById(R.id.subIdtextView);
hiddenView.setText(currentLVItem.getId());
TextView summaryView = (TextView) itemView.findViewById(R.id.subSubjectTextView);
summaryView.setText(currentLVItem.getSummary());
TextView descripView = (TextView) itemView.findViewById(R.id.subScriptTextView2);
descripView.setText(currentLVItem.getScripts());
return itemView;
}
}
private class myTopListAdapter extends ArrayAdapter<topgroupItem>{
public myTopListAdapter() {
super(MainActivity.this, R.layout.group_item, myGroupTopItems);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if(itemView == null)
{
itemView = getLayoutInflater().inflate(R.layout.group_item, parent, false);
}
topgroupItem currentTGItem = myGroupTopItems.get(position);
TextView textView = (TextView) itemView.findViewById(R.id.groupItem);
textView.setText(currentTGItem.getText());
return itemView;
}
}
}
This is what textv displays: Cursir Count = 3 subListView Count = 3 adapter2 Count: 3
I'm not sure why I am getting a Null for subListView. I'm not looking for an expanded listview with what I am doing
Sorry for all the code. Any help would be greatly appreciated
First: you call popList() in onCreate(). That is before the List gets populated with items and therefore there is no child view with the id sublistView.
Second: DO NOT ADD A LIST INTO A LIST ITEM! No ScrollViews inside another ScrollView! You might wanna check out ExpandableListView if you'd like to have sub lists.
im trying to make an activity that searches a DB based on an input string and then returns the results in a list view. All this is working however, My listview items are not clickable. I have tried changing the focus and clickable attributes but nothing has worked so far.
Main XML (add_friend_layout.xml):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout android:id="#+id/AddFriendHeaderLayout"
android:layout_marginTop="3dip"
android:layout_height="45dip"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:gravity="center">
<EditText
android:id="#+id/et_SearchFriend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:ems="10"
android:inputType="text" />
<Button
android:id="#+id/bt_SearchFriend"
android:layout_width="wrap_content"
android:layout_height="40dip"
android:focusable="false"
android:icon="#android:drawable/ic_search_category_default"
android:text="Search" >
</Button>
</LinearLayout>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="60dip"
android:layout_marginBottom="5dip"
android:layout_alignParentBottom="true"
android:layout_above="#+id/AddFriendHeaderLayout"
android:id="#+id/searchFriendFooterLayout">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:clickable="true"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
</RelativeLayout>
ListView XML (single_listview_layout.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:clickable="true" >
<TextView
android:id="#+id/tv_list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="20sp" >
</TextView>
</LinearLayout>
Main Java Function (SearchFriendActivity.java):
public class SearchFriendActivity extends ListActivity {
//Progress Dialog
private ProgressDialog pDialog;
private Button bt_searchFriend;
private EditText et_Search_String;
private ListView tv_listview;
String[] arrFriends;
String[] arrUserId;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
setContentView(R.layout.add_friend_layout);
bt_searchFriend= (Button) findViewById(R.id.bt_SearchFriend);
et_Search_String = (EditText) findViewById(R.id.et_SearchFriend);
tv_listview = (ListView) findViewById(R.id.tv_list);
String searchString="";
//searchString = String.valueOf(et_Search_String.getText());
Log.i ("log_search","value of searchString: " + searchString);
bt_searchFriend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try{
searchFriends aTask = new searchFriends();
aTask.execute(String.valueOf(et_Search_String.getText()));
String rResult = aTask.get();
// Convert aResult to array
arrFriends = convertJSONData(rResult);
arrUserId = convertJSONDataToUserArray(rResult);
setListAdapter(new ArrayAdapter<String>
(getBaseContext(),
R.layout.single_listview_layout,
R.id.tv_list,
arrFriends));
}catch(Exception e){
Log.e ("log_search_load",e.toString());
}
}
});
tv_listview = getListView();
//handler for List Item click
tv_listview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(),
"Friend request sent for " +
((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
Log.i("log_search_listclick", "Listview clicked");
}
});
}catch(Exception e){
Log.e ("log_search_load2",e.toString());
}
}
Firstly, don't use focusable and clickable. When you use setOnclick or another they are auto creating.
Secondly, remove try cache blog then start application. Because when the problem created program will contining and you can't understand where is the problem.
===>Thirdly<====
you are used (tv_listview=...) second twice
tv_listview = (ListView) findViewById(R.id.tv_list);
tv_listview = getListView();
then you are trying tv_listview.setOnItemClickListener..... If second view is not first view seton not working on "R.id.tv_list".