this is my saveddata.java page who can I solve
when I want to update data its say number expectation
and data insert but not update
I am trying to take the input values from EditText and I want to save it to SQLite Database. I don't know how to use the logcat [also please explain how can I read the errors from the LogCat].
package com.turningpoint.currencycounter;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class saveddata extends Activity{
DBHelper mydb;
private ListView obj;
ListViewAdapter lviewAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.saveditem);
ListViewAdapter arrayAdapter;
mydb = new DBHelper(this);
List<String> friendsnames= mydb.getAllCotacts();
List<String> friendsnames2= mydb.getAllCotacts2();
String frnames[]=friendsnames.toArray(new String[friendsnames.size()]);
String frnames2[]=friendsnames2.toArray(new String[friendsnames2.size()]);
arrayAdapter = new ListViewAdapter(this, frnames, frnames2);
obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
obj.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
// TODO Auto-generated method stub
int id_To_Search = arg2;
List array_list = mydb.getAllCotacts();
String s = array_list.get(id_To_Search).toString();
Cursor c2 = mydb.getData4(s);
while (c2.moveToNext()) {
String id = c2.getString(0);
String code = c2.getString(1);
// String code ..give me Number inut Expetation
int id2 = Integer.parseInt(id);
int code2 = Integer.parseInt(code);
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id2);
int update=1;
dataBundle.putInt("update", update);
dataBundle.putInt("code", code2);
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
intent.putExtras(dataBundle);
Toast.makeText(getApplicationContext(), code, Toast.LENGTH_SHORT).show();
startActivity(intent);
}
Toast.makeText(getApplicationContext(), s,Toast.LENGTH_SHORT).show();
}
});
}
}
Use android:inputType="number" in EditText to make sure that the input is a number not a string or a charater like this
<EditText
.
.
.
android:inputType="number"
/>
Another solution:
Check if it is a number programmatically
boolean digitsOnly = TextUtils.isDigitsOnly(editText.getText());
Read this article. You will know how to use the logcat
https://guides.codepath.com/android/Debugging-Exceptions-within-your-App
I solve this problem
int code2 = Integer.parseInt(code);
this c2.getString(1) could not Int its give me String
Related
I have a database with for Columns {id,eng,kurd,ar} and I have populated a listview from it that shows only {eng} from the databse. I want to pass the {eng,kurd,ar} which have the same {id} when the user clicks an item in the listview, but when I click an item my app crashes, but everything else works fine there is no error in non of the other classes[adapter,sqliteopenhelper]
MainActivity.class
package com.rawa.rawadict;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
Adapter adapter;
ArrayList<Item> myList = new ArrayList<Item>();
ListView myListView;
Databasehelper myDbHelper = new Databasehelper(this);
String engRes,kurdRes,arRes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
myDbHelper.createDatabase();
myDbHelper.openDatabase();
} catch (IOException e) {
throw new Error("Unable to create database");
}
Cursor cursor = myDbHelper.QueryData("select * from zankodict");
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
Item itemm = new Item();
itemm.setId(cursor.getString(0));
itemm.setEng(cursor.getString(1));
myList.add(itemm);
} while (cursor.moveToNext());
}
}
adapter = new Adapter(this, R.layout.single_row, myList);
myListView = (ListView) findViewById(R.id.lView);
myListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView text_id = (TextView) view.findViewById(R.id.tid);
String sel_id = text_id.getText().toString();
Cursor cursor = myDbHelper.QueryData("SELECT * FROM zankodict WHERE id =" + sel_id);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
engRes = cursor.getString(1);
kurdRes=cursor.getString(2);
arRes= cursor.getString(3);
} while (cursor.moveToNext());
}
}
// create intent to start another activity
Intent intent = new Intent(MainActivity.this, Result.class);
// add the selected text item to our intent.
Bundle extras = new Bundle();
extras.putString("eng",engRes);
extras.putString("kurd",kurdRes);
extras.putString("ar",arRes);
intent.putExtras(extras);
startActivity(intent);
}
}) ;
}
}
Result.class
package com.rawa.rawadict;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import java.io.IOException;
import java.util.ArrayList;
public class Result extends AppCompatActivity {
TextView etView2,ktView2,atView2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_view);
etView2 = (TextView) findViewById(R.id.etextView2);
ktView2 = (TextView) findViewById(R.id.ktextView2);
atView2 = (TextView) findViewById(R.id.atextView2);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String enG = extras.getString("eng");
String kurD = extras.getString("kurd");
String aR = extras.getString("ar");
etView2.setText(enG);
etView2.setText(kurD);
etView2.setText(aR);
}
}
I want to pass the Bundle to Result.class
The best approach to passing data from activity to activity and particularly from your database is to pass an (id) as an intent extra then when you arrive at the destination activity, extract it and use it to query your database based on that id.
This will reduce the amount of data you will have to pass through your intent instance.
If you only want to pass 3 items however, you can use intent extras instead of a Bundle like this:
Intent intent = new Intent(MainActivity.this, Result.class);
intent.putExtra("eng",engRes);
intent.putExtra"kurd",kurdRes);
intent.putExtra("ar",arRes);
startActivity(intent);
To extract this in your Results activity;
Intent intent = getIntent();
String enG = intent.getExtras().getString("eng");
String kurD = intent.getExtras().getString("kurd");
String aR = intent.getExtras().getString("ar");
I hope this helps and good luck!
I am developing one android application.i want to display a data which is selected from database and display it in listview.first of all i had used static data for display Trainee(user) data. which is static. then after For same functionality i have use sqlite Database and register the Trainee(user) and now i want to display registered trainne's name in listview. i have just done below code. can anyone help me how to display trainee names in listview.
AddTraineeActivity.java
This file works basic function of create trainee database and insert values of trainee:
package com.example.gymapp;
import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class AddTraineeActivity extends Activity implements OnClickListener
{
EditText fn;
EditText ln;
EditText un;
EditText pwd;
EditText pno;
EditText age;
Button btnAdd;
SQLiteDatabase db = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_managetrainee);
fn = (EditText) findViewById(R.id.etfirstname);
ln = (EditText) findViewById(R.id.etlastname);
age = (EditText) findViewById(R.id.edage);
pno = (EditText) findViewById(R.id.etphoneno);
un = (EditText) findViewById(R.id.ettraineeun);
pwd = (EditText) findViewById(R.id.etpwdtrainee);
btnAdd = (Button) findViewById(R.id.btnsavedata);
db=openOrCreateDatabase("mydb", MODE_PRIVATE, null);
db.execSQL("create table if not exists trainee(firstname text, lastname text,age varchar,phoneNumber varchar,userTrainee varchar,passwordTrainee varchar)");
btnAdd.setOnClickListener(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
public void show(String str)
{
Toast.makeText(this, str, Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v== btnAdd)
{
String firstname = fn.getText().toString();
String lastname = ln.getText().toString();
String Age = age.getText().toString();
String phoneNumber = pno.getText().toString();
String usernameTrainee = un.getText().toString();
String passwordTrainee = pwd.getText().toString();
if(firstname==null||firstname==""||firstname.length()<3)
{
show("Please Enter Correct Name.");
}
else if(lastname==null||lastname==""||lastname.length()<2)
{
show("Please Enter Correct Name.");
}
else if(Age==null||Age==""||Age.length()>3)
{
show("Please Enter Correct Age.");
}
else if(phoneNumber==null||phoneNumber==""||phoneNumber.length()<10)
{
show("Please Enter Correct mobile number.");
}
else if(usernameTrainee==null||usernameTrainee==""||usernameTrainee.length()<4)
{
show("Please Enter valid User name.");
}
else if(passwordTrainee==null||passwordTrainee==""||passwordTrainee.length()<6)
{
show("Please Enter Strong Password.");
}
else
{
db.execSQL("insert into trainee values('"+firstname+"','"+lastname+"','"+Age+"','"+phoneNumber+"','"+usernameTrainee+"','"+passwordTrainee+"')");
//i=new Intent(this,Welcome.class);
//startActivityForResult(i, 500);
//overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
db.close();
finish();
}
}
}
}`
UserListActivity.java
This file contain the code which display the trainee names in listview. but this file display static users for example,trainee1,trainee2,trainee3....trainee13.
package com.example.gymapp;
import com.tss.constant.Constant;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.content.Context;
import android.database.sqlite.*;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.Cursor;
import com.example.gymapp.AddTraineeActivity;
import com.example.gymapp.dao.DBfitguidehelper;
public class UserListActivity extends Activity {
private ListView listViewUser;
private String loggedInType ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_list);
//SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
//queryBuilder.setTables(DBfitguidehelper.)
listViewUser = (ListView)findViewById(R.id.listViewUser);
String[] values = new String[]{"trainee", "trainee1", "trainee2", "trainee3", "trainee4", "trainee5", "trainee6", "trainee7", "trainee8", "trainee9", "trainee10", "trainee11", "trainee12", "trainee13"};
ArrayAdapter<String> userAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, android.R.id.text1, values);
listViewUser.setAdapter(userAdapter);
listViewUser.setOnItemClickListener(new ListViewListner());
if(savedInstanceState!=null){
Bundle extras = getIntent().getExtras();
loggedInType = extras.getString("loggedInType");
System.out.println("loggedInType - " + loggedInType);
}
}
private class ListViewListner implements OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "selected user is " + listViewUser.getItemAtPosition(position), Toast.LENGTH_SHORT).show();
Constant.Selected_Trainee = ""+listViewUser.getItemAtPosition(position);
Intent intent = new Intent(getApplicationContext(),TrainerActivity.class);
intent.putExtra("loggedInType", loggedInType);
Toast.makeText(getApplicationContext(), "loggedInType"+loggedInType, Toast.LENGTH_SHORT).show();
startActivity(intent);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.user_list, menu);
return true;
}
}
now i want to display name of trainees which is stored in database. can anyone help me??
If you want to see how a Cursor loader can work for you, you can review the following project that I have uploaded to github: GPS Distance Tracking
I am very new to this API.I have knowledge on doing samples with this API.after that my requirement is display the Column graph based on Spinner Values selection .the query table data is coming correctly the problem is not appending the latest values to the chart .
In My App i have one spinner name it as Customer Name:
when i change the spinner-value i am sending the Customer name to input parameter to sqllite and display the graph for that i write the following code.
package com.appulento.salestracking;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Vector;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import com.appulento.salestrackingdb.DBAdapter;
import com.artfulbits.aiCharts.ChartView;
import com.artfulbits.aiCharts.Base.ChartArea;
import com.artfulbits.aiCharts.Base.ChartAxis;
import com.artfulbits.aiCharts.Base.ChartCollection;
import com.artfulbits.aiCharts.Base.ChartCollection.IChangeListener;
import com.artfulbits.aiCharts.Base.ChartNamedCollection;
import com.artfulbits.aiCharts.Base.ChartPalette;
import com.artfulbits.aiCharts.Base.ChartPoint;
import com.artfulbits.aiCharts.Base.ChartSeries;
import com.artfulbits.aiCharts.Types.ChartTypes;
public class SalesTrackingByCustomer extends Activity {
private DBAdapter db;
private Spinner spinner1, spinner2;
private String[] prodctnames;
private String[] prodctnames1;
private double[] product_1;
private double[] product_2;
public int count;
public String custid;
public Sample customerdetails;
public ChartCollection<String> collection;
ChartArea area;
ChartArea area1;
private SimpleAdapter mSchedule;
Vector<String> vec_custid=new Vector<String>();
Vector<String> vec_oldno=new Vector<String>();
Vector<String> vec_productid=new Vector<String>();
Vector<String> vec_qty=new Vector<String>();
private ListView mListView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bycustomers);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
mListView=(ListView)findViewById(R.id.listView1);
prodctnames=new String[10];
product_1=new double[10];
prodctnames1=new String[10];
product_2=new double[10];
db=new DBAdapter(this);
final ChartView chartView = (ChartView) findViewById(R.id.chartView);
ChartPalette palette = new ChartPalette(0xffffd7e8);
chartView.setPalette(palette);
final ChartSeries product1 = new ChartSeries("P1", ChartTypes.Column);
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
int position=spinner1.getSelectedItemPosition();
System.out.println("=====ITEM POSITION======"+position);
final String selected=arg0.getItemAtPosition(arg2).toString();
System.out.println("=====IN SELECTED======"+selected);
//finish();
db.open();
Cursor customer=db.fetchorderCustomername(selected);
custid=customer.getString(0);
System.out.println("=====CUSTOMER NAME ID======"+custid);
Cursor cursor=db.fetchorderDetails(custid);
count=cursor.getCount();
System.out.println("=====COUNT======"+count);
int i=0;
while (i<count)
{
String productid=cursor.getString(1);
prodctnames[i]=productid;
String qty=cursor.getString(2);
product_1[i]=Double.parseDouble(qty);
System.out.println("=====PROID======"+prodctnames[i]+"=====QUANTITY======"+product_1[i]);
cursor.moveToNext();
i++;
}
for (int j = 0; j < count; j++)
{
ChartPoint point = product1.getPoints().addXY(j, product_1[j]);
point.setAxisLabel(prodctnames[j]);
}
if(position==0)
{
chartView.refreshDrawableState();
chartView.getSeries().add(product1);
area = chartView.getAreas().get(0);
area.getDefaultXAxis().setLabelsMode(ChartAxis.LabelsMode.SeriesLabels);
}
if(position==1)
{
chartView.refreshDrawableState();
chartView.getSeries().add(product1);
area1 = chartView.getAreas().get(0);
area1.getDefaultXAxis().setLabelsMode(ChartAxis.LabelsMode.SeriesLabels);
}
//area.refresh();
db.close();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
My problem is at first time Application Launch the graph is Displaying successfully when i change the Spinner value selection the app got closed and display the fallowing exception in my log cat:
java.security.InvalidParameterException: This name already presents at com.artfulbits.aiCharts.Base.ChartNamedCollection.validateName(SourceFile:128 ) at com.artfulbits.aiCharts.Base.ChartNamedCollection.validate
please see once and let me know where i am doing Mistake in my code.The dynamic vlaues is not appending to that chart in the above code.
Thanks in Advance....
The problem is that you're trying to add new area with the same name. I'm not exactly well versed in the API enough, but i'd imagine that the issue comes when you try this line a second time:
chartView.getSeries().add(product1);
I also noticed that you never used the following:
prodctnames1=new String[10];
product_2=new double[10];
If i could make a suggestion, perhaps it isn't best to have all your code in a click listener. maybe you can fill your datasets at the beginning and then only show the graphs upon using the spinner. Because if one clicks the spinner more than once, you have to go to the database to get the same information.
I am trying to display the steps to a recipe, the recipe is stored in a string array.
Im trying to get each step to be inserted into a text view, and have the following code:
public class MethodActivity extends ListActivity{
ListView recipes;
Intent myIntent;
String value;
TextView editvalue;
Intent intent;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recipemethod);
editvalue = (TextView)findViewById(R.id.method);
value = getIntent().getStringExtra("searchValue");
editvalue.setText(value);
final String[] words = getResources().getStringArray(R.array.Lasagna);
final TextView tw=(TextView)findViewById(R.id.method);
for(int item = 0;item<words.length;item++){
tw.setText(words [item]);
}
}
}
I am also wanting to make it dynamic so does anyone know how I can do that? (e.g. depending on what the user clicked that recipe is shown).
Thanks
It might be easier to actually use your ListActivity's ListView... You can even show your recipe in another ListView, as it will undoubtedly be more intuitive for the user...
A simple code that does this would go somewhat in the following lines:
File 1: RecipeListActivity.java (shows list of recipes)
package com.epichorns.testproject;
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class RecipeListActivity extends ListActivity {
final Recipe[] mRecipesArray = { new Recipe("Lasagna", new String[]{"Some lasagna noodles", "Some tomato sauce"}),
new Recipe("PortalCake", new String[]{"GlaDOS' wit","Is a lie"}),
new Recipe("EarthDestruction", new String[]{"Asteroid", "Kinetic energy"})};
public class Recipe{
public String name;
public String[] steps;
Recipe(String name, String[] steps){
this.name = name;
this.steps = steps;
}
}
public ArrayList<String> FetchRecipesRawArray(Recipe[] recipes){
ArrayList<String> ret = new ArrayList<String>();
for(int i=0;i<recipes.length;i++){
ret.add(recipes[i].name);
}
return ret;
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, FetchRecipesRawArray(mRecipesArray));
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id){
Intent intent = new Intent(this, RecipeActivity.class);
intent.putExtra(RecipeActivity.EXTRA_RECIPEARRAY, mRecipesArray[position].steps);
startActivity(intent);
}
}
File 2: RecipeActivity.java (shows a recipe in a list)
package com.epichorns.testproject;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
public class RecipeActivity extends ListActivity {
final static public String EXTRA_RECIPEARRAY = "recipeArray";
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
String[] recipeArray = getIntent().getStringArrayExtra(EXTRA_RECIPEARRAY);
if(recipeArray!=null){
if(recipeArray.length>0){
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, recipeArray);
setListAdapter(adapter);
}
}
}
}
Alternately, here is a code which composites a TextView below the recipes list in order to show the recipe content without opening another Activity:
File: RecipeListActivity.java
package com.epichorns.testproject;
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class RecipeListActivity extends ListActivity {
final Recipe[] mRecipesArray = { new Recipe("Lasagna", new String[]{"Some lasagna noodles", "Some tomato sauce"}),
new Recipe("PortalCake", new String[]{"GlaDOS' wit","Is a lie"}),
new Recipe("EarthDestruction", new String[]{"Asteroid", "Kinetic energy"})};
TextView mTextView_recipeTitle;
TextView mTextView_recipe;
public class Recipe{
public String name;
public String[] steps;
Recipe(String name, String[] steps){
this.name = name;
this.steps = steps;
}
}
public ArrayList<String> FetchRecipesRawArray(Recipe[] recipes){
ArrayList<String> ret = new ArrayList<String>();
for(int i=0;i<recipes.length;i++){
ret.add(recipes[i].name);
}
return ret;
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTextView_recipe = (TextView)findViewById(R.id.recipeText);
mTextView_recipeTitle = (TextView)findViewById(R.id.recipeTitle);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, FetchRecipesRawArray(mRecipesArray));
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id){
mTextView_recipeTitle.setText(mRecipesArray[position].name);
mTextView_recipe.setText("");
String[] recipeSteps = mRecipesArray[position].steps;
for(int i=0;i<recipeSteps.length;i++){
mTextView_recipe.append(recipeSteps[i]+"\n");
}
}
}
File: main.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="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:background="#400000FF"
/>
<TextView
android:id="#+id/recipeTitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#4000FF00"
/>
<TextView
android:id="#+id/recipeText"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#40FF0000"
/>
</LinearLayout>
You will want to use tw.append() instead of setText, otherwise all you will ever see is the last string in the array.
Make it dynamic, I would use a fragments (using the Android Support Library if on older android versions) model, load each array, attaching the string array as a bundle to the fragment before launching.
Fragment tut:http://developer.android.com/guide/topics/fundamentals/fragments.html
Support library: http://developer.android.com/training/basics/fragments/support-lib.html
I can't get my ListView work. When i run emulator it doesn't display ListView with data from databse wihich I created.
I would like to insert data to database through EditText and then display data
Main Program
package test.test;
import java.util.ArrayList;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class TestActivity extends Activity {
/** Called when the activity is first created. */
private ListView listview;
private TextView textview;
private Button button;
private EditText edittext;
SQLiteDatabase databas;
//private String[] test = {"abc","abc","abc", "abc", "abc", "abc"};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<String> test2 = new ArrayList<String>();
listview = (ListView)findViewById(R.id.test);
textview = (TextView)findViewById(R.id.mm);
button = (Button)findViewById(R.id.kanp);
edittext = (EditText)findViewById(R.id.textetid);
databas = (new dbHelper(this)).getWritableDatabase();
final ContentValues values = new ContentValues();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Editable ord = edittext.getText();
String ordDb = ord.toString();
//String sql = "INSERT INTO ordlista (ord) " +
//"VALUES (" + ordDb + ")";
//databas.rawQuery(sql, null);
values.put("ord", ordDb);
long varde = databas.insert("ordlista", null, values);
String varde2 = Long.toString(varde);
textview.setText(varde2);
}
});
//#############################TORSDAG###############################
Cursor c = databas.rawQuery( "select ord from ordlista", null);
startManagingCursor(c);
int n = 1;
while(c.isBeforeFirst() == false){
String dbVarde = c.getString(n);
test2.add(dbVarde);
c.moveToNext();
n++;
}
ArrayAdapter<String> aa;
aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, test2);
listview.setAdapter(aa);
//listview.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, test));
}
}
You could try using a SimpleCursorAdapter and save the overhead of maintaining an ArrayAdapter. Rather than having to populate an ArrayList all the time, you can just create a Cursor against the query when you need it updated and set the ListView's adapter. A SimpleCursorAdapter also has the added benefit of handling the list item's population for you based on the columns you provide.
For example:
String[] fieldsFromDB = new String[] {"ord"};
int[] fieldsOnListItem = new int[] {android.R.id.text1};
Cursor c = databas.rawQuery("select ord from ordlista", null);
listview.setAdapter(new SimpleCursorAdapter(this,android.R.layout.simple_list_item_1,c,fieldsFromDB,fieldsOnListItem));