How do you fully setup an edittext into a ScrollView? - android

Before I go into detail about the problem I have been having, I am quite new to android development so let me just explain what I would like to achieve and what I have tried to do.
I am creating an android app in eclipse IDE using the android 4.0 operating system and what I would like to create in this app is a windowed scrollview which contains various different widgets such as check boxes, text views and edit texts. These edit texts are required so that the user can input some data about an image that is displayed in an image view on the app page but is not inside the scroll view. The user would then press a button and that data would then be stored somewhere (i know what I want to do with that) and a new image would appear, then the process repeats.
Now in order to create a windowed scrollview, I understand that you need to define the widgets inside a scrollview and to be able to scroll down to them properly is by defining them inside a linear layout and then messing around with the margin top values in each widget in the activity xml file.
However, once i created these widgets tried testing, this is where I am running into some issues.
Firstly, if a widget is placed in between the header and footer ( the region displayed on the app page and used as part of the windowed scrollview) and i try and test out the scrolling, the scrolling works but it creates a random duplicate of that widget which I cannot get rid of e.g http://community.dur.ac.uk/cs.seg05/androidapp/exhibit_A.JPG (I can't display the image to you directly as i am not a high enough rank to display an image on StackOverflow)
In an attempt to try and fix this issue, I decided that I would move everything below the footer of the scrollview and then just scroll up from there and this seemed to have worked.
Unfortunately, when trying to test out inputs into my edit texts, I ran to another annoying problems.
As soon as I finish typing into an edit text and click the next button on the soft keyboard, the app directed me to another edit text which I had not defined and displayed another soft keyboard and this in turn created a duplicate of every widget (including that edit text) that was currently displayed inside the scrollview window. (i had scrolled up in order to get to this edit text) eg
https://community.dur.ac.uk/cs.seg05/androidapp/test.JPG
I then looked on questions such as Scrolling EditText on ScrollView programmatically , How to prevent auto scrolling of EditText when keyboard appears on Android? , Enable Scrolling within EditText that is in a ScrollView
but none of these are really helping me.
I have also tried using AutoTextCompleteView widgets as the widgets that the user woudl use as inputs but I do not fully understand how they work and I have not been able to get any data from them as when i type something into them, the program is returning that nothing has been typed.
I would really appreciate some help on this as I don't know if I am missing something, or if I have not set the widgets up correctly or if I have not set the scrollview correctly so if any of you have any solutions to these problems, please post them (code or a step by step would be very helpful).
Here is my java code in my activity (note that this a second activity that is launched once the first activity is completed).
package com.example.hello;
import android.app.Activity;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import android.os.Build;
import android.widget.AdapterView.OnItemClickListener;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
public class SecondActivity extends Activity {
private String userId; //global variable as it will be used throughout this activity
private ArrayList <String> imageNames;
private String directory="http://community.dur.ac.uk/cs.seg05/Wild/CameraImages/";
private int imageNumber=0;
private CheckBox humanTest;
private ArrayList<String> pictureIds;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Bundle data = getIntent().getExtras(); //obtains information passed from the previous activity
userId= data.getString("userId"); //gets the user id from the main activity
System.err.println("Received User id " +userId);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
imageNames =getImages(userId); //gets all of the image names from the database
System.err.println(imageNames);
getNextImage(imageNumber, imageNames); //method that obtains the next image
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_second,
container, false);
return rootView;
}
}
public ArrayList<String> getImages(String userid) { // method that gets images from a php file
ArrayList<String> images= new ArrayList<String>();
pictureIds= new ArrayList<String> ();
try {
HttpClient httpclient= new DefaultHttpClient();
URI website= new URI("https://community.dur.ac.uk/cs.seg05/androidapp/ImageAccess.php?userid="+userid);
HttpGet request= new HttpGet();
request.setURI(website);
HttpResponse response = httpclient.execute(request);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb=new StringBuffer("");
String l= "";
String nl= System.getProperty("line.separator");
while ((l = reader.readLine()) != null) { //converts the whole output into a string
sb.append(l+ nl);
}
reader.close();
String result=sb.toString();
JSONArray jArray = new JSONArray(result);
System.err.println(jArray.length());
for(int i=0;i<jArray.length();i++){ //retrieves the JSon
JSONObject json_data = jArray.getJSONObject(i);
System.err.println(json_data);
images.add(json_data.getString("File_Name"));
pictureIds.add(json_data.getString("Picture_ID"));
}
}
catch (Exception e) {
System.err.println(e);
}
return images;
}
public static Bitmap getBitmapFromURL(String src) {
try {
java.net.URL url = new java.net.URL(src);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public void getNextImage(int number, ArrayList<String> images) { //method that gets the images
if (number>=images.size()) {
String whitespace="http://www.skettymethodistchurch.org.uk/whitespace.jpg" ; //whitespace for when user has finished the subset of images
Bitmap bm= getBitmapFromURL(whitespace);
ImageView iv= (ImageView)findViewById(R.id.imageView1); //gets the image view
iv.setImageBitmap(bm);
}
else {
String image=images.get(number);
String request=directory+image;
Bitmap bm= getBitmapFromURL(request);
ImageView iv= (ImageView)findViewById(R.id.imageView1); //gets the image view
iv.setImageBitmap(bm);
imageNumber++;
}
}
public void loadNextImage(View view) { //method for when the next button is clicked
try {
// humanTest = (CheckBox) findViewById(R.id.checkBox1);
ImageView iv= (ImageView)findViewById(R.id.imageView1); //gets the image view
iv.setImageBitmap(null);
getNextImage(imageNumber, imageNames);
}
catch (Exception e) {
System.err.println(e);
}
}
public void LoadHelpActivity(View view) {
Intent i = new Intent(getBaseContext(), HelpActivity.class);
startActivity(i);
}
public void getScore(View view) {
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
}
}
Here is the xml file associated with this activity:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:id="#+id/container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context="com.example.hello.SecondActivity"
tools:ignore="MergeRootFrame" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="315dp"
android:layout_height="150dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="38dp" />
<!-- Header aligned to top -->
<RelativeLayout
android:id="#+id/header"
android:layout_width="315dp"
android:layout_height="35dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:gravity="center" >
<TextView
android:layout_width="355dp"
android:layout_height="25dp"
android:layout_marginTop="0dp"
android:text="Scroll up to classify the contents of the image"
android:textColor="#000"
android:textSize="14sp" />
</RelativeLayout>
<!-- Footer aligned to bottom -->
<RelativeLayout
android:id="#+id/footer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:gravity="center" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
/>
</RelativeLayout>
<ScrollView
android:id="#+id/scrollableContents"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_above="#id/footer"
android:layout_below="#id/header"
android:isScrollContainer="false"
android:fillViewport="true"
>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical" >
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:text="Humans in image" />
<EditText
android:id="#+id/EditText01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="text"
android:layout_marginTop="30dp"
android:ems="13"
/>
<Button
android:id="#+id/button1"
android:layout_width="95dp"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:layout_centerHorizontal="true"
android:onClick="loadNextImage"
android:text="#string/classify" />
</LinearLayout>
</ScrollView>
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:onClick="LoadHelpActivity"
android:text="Help" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_alignLeft="#+id/imageView1"
android:layout_alignParentTop="true"
android:layout_marginLeft="22dp"
android:onClick="getScore"
android:text="Check score" />
</RelativeLayout>
Finally, here is the android manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.hello"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="14" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.hello.MainActivity"
android:label="Wild Eyes" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.hello.SecondActivity"
android:label="Wild Eyes" >
</activity>
<activity
android:name="com.example.hello.HelpActivity"
android:label="Wild Eyes" >
</activity>
</application>
</manifest>
If there is anything that I have missed and that would be beneficial, do let me know and I will post it.
Thanks
Tom

Related

button onclick from a layout file

so I was working on some basics of android when I stumbled upon this. I am trying to implement a listview(having its layout stored in file eachrow.XML)and a button on my app such that when the user clicks one button "schoollife", the listview automatically imports layout stored from other file "eachrow2.XML".
the layout of eachrow.xml consists of buttons only, while the layout of eachrow2.xml consists of buttons.
Everything seems to work fine, the user clicking the button imports the other layout , but the problem starts when user tries to click buttons from the second layout. in the error logs, it is stating that the button 'subject' causing a null pointer exception
eachrow.xml:
eachrow2.xml:
===========codes========
eachrow2.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="horizontal">
<Button
android:id="#+id/subjectbutton"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:padding="1dp"
android:layout_margin="1dp"
android:textAllCaps="false"
android:background="#color/colorPrimary"
android:textColor="#color/white"
/>
<TextView
android:id="#+id/marksbox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="20dp"
android:text="click the button to show marks of each subject"
android:textAlignment="center"
/>
</LinearLayout>
mainactivity.java:
package com.example.ansh.reportcard;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private ListView l;
private String[] d_myself;
private ArrayAdapter adp;
private HashMap<String,String> d_school;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l=(ListView)findViewById(R.id.a_list);
d_myself= new String[]{"something"
};
d_school=new HashMap<>();
d_school.put("A","B");
Button B_myself= (Button)findViewById(R.id.myself);
B_myself.setOnClickListener(this);
Button B_school=(Button)findViewById(R.id.school);
B_school.setOnClickListener(this);
Button subject=(Button)findViewById(R.id.subjectbutton);
subject.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if(view.getId()==R.id.myself){
adp=new ArrayAdapter(MainActivity.this,R.layout.eachrow,R.id.textView,d_myself);
l.setAdapter(adp);
}
if (view.getId()==R.id.school){
adp=new ArrayAdapter(MainActivity.this,R.layout.eachrow2,R.id.subjectbutton,d_school.keySet().toArray());
l.setAdapter(adp);
}
if (view.getId()==R.id.subjectbutton){
Button tmp=(Button)view;
CharSequence x=tmp.getText();
TextView t= (TextView) findViewById(R.id.marksbox);
t.setText(d_school.get(x.toString()));
}
}
}
According to my understanding to your question, You declaring the Button from the xml file activity_main.xml, Instead you should find it from the eachrow2.xml file.
The subjectbutton is in the eachrow2.xml so you need to find the view from this file only instead activity_main.xml.

App was unable to start Android

Getting the error "Unable To start myWeb*(my app's name)*"
Can anybody Help me ?
I am a newbie and just started coding android.
I ran this on eclipse and when the app is launched from ADT it gave error!!
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myweb"
android:versionCode="1"
android:versionName="1.0"
android:name="testing.android.application.three.MainActivityThreeActivity"
>
<uses-permission android:name="android.permission.INTERNET"
/>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.myweb.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
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:background="#style/AppTheme"
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"
android:id="#+id/mainLayout"
>
<EditText
android:id="#+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="105dp"
android:ems="10"
android:textColor="#00FF00"
android:typeface="monospace"
android:hint="Email Address or Phone Number" />
<EditText
android:id="#+id/password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/password"
android:layout_centerVertical="true"
android:ems="10"
android:textColor="#00FF00"
android:typeface="monospace"
android:hint="Password"
android:inputType="textPassword"/>
<Button
android:id="#+id/login1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/password"
android:layout_below="#+id/password"
android:layout_marginTop="18dp"
android:minWidth="180dip"
android:text="Log In" />
<ProgressBar
android:id="#+id/progressBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/login1"
android:layout_toRightOf="#+id/login1"
android:visibility="invisible" />
</RelativeLayout>
MainActivity.java
package com.example.myweb;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton button = (ImageButton) findViewById(R.id.login1);
EditText emailBox = (EditText)findViewById(R.id.email);
EditText passwordBox = (EditText)findViewById(R.id.password);
final String emailId = emailBox.getText().toString();
final String passwordId = passwordBox.getText().toString();
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
getUserLoggedIn(emailId,passwordId);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void getUserLoggedIn(String email,String password) throws ClientProtocolException, IOException{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("localhost/testand.php");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("email", email));
pairs.add(new BasicNameValuePair("password", password));
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(post);
}
}
Use AsyncTask like below and call it in onCreate
private class DownloadFilesTask extends AsyncTask<emailId, passwordId> {
protected Long doInBackground(URL... urls) {
getUserLoggedIn(emailId,passwordId);
return totalSize;
}
protected void onPostExecute(Long result) {
Log.v("Webpage","Done");
}
}
and call in onCreate
try {
new DownloadFilesTask().execute(emailId,passwordId);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Solved It!![Solution Here]
Actually this was solved....
In activity_main.xml i used <button> tag but in .java i used ImageButton to call it by id.
Though silly i solved it by using Button class instead of ImageButton in java file
Changed
ImageButton button = (ImageButton) findViewById(R.id.login1);
to
Button button = (Button) findViewById(R.id.login1);
This fix was only specific to my code. So if anybody gets around error like this its time to recheck code rather than hanging around with Questions.

Android: Displaying an ArrayList<HashMap<String, String>> to screen using ListFragment

I'm trying to read a text file into my android app and then print the contents of the file to screen across 3 columns.
The text file will be in the format of "column 1 data - column 2 data - column 3 data" on each line. I'm reading the information into an ArrayList> and then trying to print it to screen. I have two xml files that i'm working with.
The one containing my list
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:paddingTop="4dip"
android:paddingBottom="6dip"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
and the one containing my TextViews
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:paddingTop="4dip"
android:paddingBottom="6dip"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TextView android:id="#+id/flitem"
android:layout_width="50dip"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/flgrams"
android:layout_width="70dip"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<TextView android:id="#+id/flpointsLayout"
android:layout_width="60dip"
android:layout_height="wrap_content"
android:layout_weight="1"/>
</RelativeLayout>
I have two lists specified in the first xml because when I had the android:name as
android:id="#android:id/list"
I couldn't like select the list using R.id.list but if I specified it using
android:id="#+id/list"
I was getting a null pointer exception.
My code in my Class extending ListFragment is as follows
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class FoodListFragment extends ListFragment {
ArrayList<HashMap<String, String>> myList;
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
createHashMap(activity);
} catch (Exception e){
System.out.println("Caught Exception: " + e);
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.foodlistmenu, container, false);
ListView list = (ListView) rootView.findViewById(R.id.list);
SimpleAdapter pointsListAdapter = new SimpleAdapter(getActivity(), myList, R.layout.foodlistmenu, new String[] {"Item", "Qty/Weight", "Points"}, new int[] {R.id.flitem, R.id.flgrams, R.id.flpointsLayout});
try {
list.setAdapter(pointsListAdapter);
} catch (Exception e) {
System.out.println("Caught Exception Setting adapter to list. Exception is: " + e);
}
return rootView;
}
public void createHashMap(Activity c) throws IOException{
myList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
InputStream is = c.getAssets().open("pointslist.bc");
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String line = "";
while ((line = in.readLine()) != null) {
String parts[] = line.split("-");
map.put("Item", parts[0]);
map.put("Weight", parts[1]);
map.put("Points", parts[2]);
myList.add(map);
map = new HashMap<String, String>();
}
in.close();
}
}
When I run the application (Via Emulator) I can open the page and it will just display a blank white page. But from putting in System.out.println's here and there I can see that the ArrayList> is being populated and that the List and SimpleAdapter are being successfully created and the Adapter is being set to the list without throwing any errors.
I'm relatively new to android dev and I don't get to code as much as I'd like to so I could be making some foolish mistakes (Hopefully not!). Any help on this would be extremely appreciated as I have been stuck on this for days now!
Thanks!

Android: duplicate items in ListVew. Maybe getView() called too many times?

I am trying to create a simple program which displays a "shopping
cart" list of items, along with a few buttons below it to manage the
cart.
The biggest problem is that items are getting duplicate entries in the
list view. That is, for every item I want to enter I see it appear
two times in the list view. What's the problem? Also, the scrollable
area of my cart is not big enough. How do I set it so that it is
bigger but I can still see my buttons? Perhaps I should put the
buttons above the cart?
Here is my shopping cart's layout XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Shopping Cart" />
<ScrollView android:id="#+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="110px">
<ListView
android:id="#+id/BookList"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</ListView>
</ScrollView>
<Button android:text="Add Another Book"
android:id="#+id/AddAnother"
android:layout_width="250px"
android:textSize="18px"
android:layout_height="55px">
</Button>
<Button android:text="Checkout"
android:id="#+id/Checkout"
android:layout_width="250px"
android:textSize="18px"
android:layout_height="55px">
</Button>
</LinearLayout>
Here is the layout for individual row items:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="8dip">
<LinearLayout
android:orientation="vertical"
android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="fill_parent">
<TextView
android:id="#+id/BookTitle"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:singleLine="true"
android:gravity="center_vertical"
/>
<TextView
android:id="#+id/BookPrice"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:singleLine="true"
android:ellipsize="marquee"
/>
</LinearLayout>
<Button
android:id="#+id/buttonLine"
android:gravity="center"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_alignParentRight="true"
android:text="Delete"
/>
</LinearLayout>
here is the java code for the shopping cart activity:
package com.sellbackyourbook.sellback;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import android.app.Activity;
//import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
public class cart extends Activity
{
private ListView m_bookListView;
private BookAdapter m_adapter;
//private static String[] data = new String[] = { ""
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState)
{
ShoppingCartSingleton shoppingCart = ShoppingCartSingleton.getInstance();
super.onCreate(savedInstanceState);
setContentView(R.layout.shoppingcart);
this.m_adapter = new BookAdapter(this, R.layout.cartitem,
shoppingCart.m_books);
m_bookListView = (ListView) findViewById(R.id.BookList);
m_bookListView.setAdapter(this.m_adapter);
//setListAdapter(this.m_adapter);
if (shoppingCart.m_books != null && shoppingCart.m_books.size() > 0)
{
//m_adapter.notifyDataSetChanged();
try
{
//m_adapter.clear();
//for(int i=0;i<1;i++)
Log.i("ARRAY", "m_books.size() before loop" + shoppingCart.m_books.size());
int size = shoppingCart.m_books.size();
for(int i=0;i<size;i++)
{
Log.i("ARRAY", "size in loop" + size);
Log.i("ARRAY", "adding item to adapter" + i);
m_adapter.add(shoppingCart.m_books.get(i));
}
} catch (RuntimeException e) {
e.printStackTrace();
}
//m_adapter.notifyDataSetChanged();
}
Button buttonAddAnother = (Button) findViewById(R.id.AddAnother);
buttonAddAnother.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
});
// TODO: only show this button if the shopping cart is not empty
Button buttonCheckout = (Button) findViewById(R.id.Checkout);
buttonCheckout.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
// TODO: open sellbackyourbook website using book ISBNs
ShoppingCartSingleton shoppingCart = ShoppingCartSingleton.getInstance();
String isbnList = "";
String checkoutURL = "http://www.sellbackyourbook.com/androidcart.php?isbn=";
for (Iterator<Book> i = shoppingCart.m_books.iterator(); i.hasNext(); )
{
Book currentBook = (Book) i.next();
isbnList = isbnList + currentBook.getBookISBN() + ",";
}
checkoutURL = checkoutURL + isbnList;
Log.i("CHECKOUT URL", "checkout URL to submit: " + checkoutURL);
Intent myIntent = new Intent(Intent.ACTION_VIEW);
myIntent.setData(Uri.parse(checkoutURL));
startActivity(myIntent);
}
});
}
private class BookAdapter extends ArrayAdapter<Book> {
private ArrayList<Book> books;
public BookAdapter(Context _context, int _textViewResourceId, ArrayList<Book> _books)
{
super(_context, _textViewResourceId, _books);
this.books = _books;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
System.out.println("getView " + position + " " + convertView);
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.cartitem, null);
}
Book b = books.get(position);
if (b != null)
{
TextView bTitle = (TextView) v.findViewById(R.id.BookTitle);
TextView bPrice = (TextView) v.findViewById(R.id.BookPrice);
if (bTitle != null)
{
bTitle.setText(b.getBookTitle());
}
if (bPrice != null)
{
bPrice.setText(b.getBookPrice());
}
}
return v;
}
}
}
Here is the Java code for my shopping cart. Am I using the singleton correctly? I really just wanted a quick and dirty way to allow multiple activities access to the shopping cart, as a different activity actually grabs the books from the user and this activity displays them in the cart.
I had an issue iterating through the books in onCreate() as well. the size() function kept increasing in the loop for some reason, so I changed the code and added a "size" variable to avoid making the size() call in the loop itself. I'm not really sure what that was all about.
I'm doing exactly the same thing and my getView is not called at all.
here is the script I was inspired by maybe it would help :
http://mfarhan133.wordpress.com/2010/10/14/list-view-tutorial-for-android/
Yes you are right at the point of BookAdapter's constructor. But the getView() method of BookAdapter is wrong. Please have a look at http://www.youtube.com/watch?v=wDBM6wVEO70 (from Google) to get the right way on how to work with ListView.
Removing the loop where I had this fixed the problem:
m_adapter.add(shoppingCart.m_books.get(i));
It seems like the BookAdapter constructor already took care of populating it, so I was duplicating the items by using the add() method.

for science project I'm direct messaging twitter with twitter4j lib and android 2.1 but app immediately crashes

I'm a complete beginner in java but I need to make this application to send commands over twitter. I'm using the twitter4J library and android 2.1. I finally have my code with no errors but when the app starts in the emulator, it immediately crashes. Has anyone done this before?
CODE(main file):
package edu.shs.SHSSRP;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import edu.shs.SHSSRP.TwitterTest;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
import android.widget.Button;
public class SHSSRP extends Activity {
/** Called when the activity is first created. */
WebView webview;
Button Forward;
Button Backward;
Button Left;
Button Right;
TwitterTest TwitTest;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Twitter twitter = new TwitterFactory().getInstance("SHSSRP","123ABC1234");
try {
Status status = twitter.updateStatus("HELLO WORLD!");
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/* Forward = (Button) findViewById(R.id.Forward);
Backward = (Button) findViewById(R.id.Backward);
Left = (Button) findViewById(R.id.Left);
Right = (Button) findViewById(R.id.Right);
webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("http://www.google.com");
TwitTest.runTest();
*/
}
}
CODE(function)
package edu.shs.SHSSRP;
import twitter4j.DirectMessage;
import twitter4j.ResponseList;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import android.app.Activity;
import twitter4j.*;
public class TwitterTest extends Activity
{
public void runTest()
{
// The factory instance is re-usable and thread safe.
Twitter twitter = new TwitterFactory().getInstance("SenderID","SenderPass");
try {
twitter.sendDirectMessage("ReceiverID", "HelloWorld");
} catch (TwitterException e) {
e.printStackTrace();
}
}
}
CODE(manifest)
simply add the uses permission for interet
CODE(layout)
<RelativeLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<WebView
android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<Button
android:id="#+id/Forward"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#id/webview"
android:text="#string/Forward" />
<Button
android:id="#+id/Left"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/Forward"
android:layout_alignParentLeft="true"
android:text="#string/Left" />
<Button
android:id="#+id/Right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#id/Forward"
android:text="#string/Right" />
<Button
android:id="#+id/Backward"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_centerHorizontal="true"
android:layout_below="#id/Right"
android:text="#string/Backward" />
thank you in advance,
Matt
In your AndroidManifest.xml file you need to specify that your application will connect to the internet.
Paste this just above the <application> node:
<uses-permission android:name="android.permission.INTERNET"/>
As the other folk have indicated, posting the stack trace would be a big help.
That being said, you might also consider switching to JTwitter. I know from first-hand experience that it works on Android, though I tend to remove the duplicate org.json classes that JTwitter has in its published JAR.

Categories

Resources