I'm really frustrated because of bad programming style, and inexperience in Android. Sorry to tell you guys that.
How the app works:
This is a todo app for my job training. There are 6 columns.
3 of these contain information about the todo and the other 3 contain a view detail, edit, and remove screen.
When the user clicks remove for some reason even after setting a notifyDataChange, my screen is not updated and the deleted row it's still displayed.
Any ideas of what is going on here? I've tried many solutions for about 3 hours now
The code is posted here sorry if its a bit tedious.
The whole class with the ListViews:
package com.DCWebMakers.Vairon;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class ManageAppointment extends Activity {
ListView rowLi, whenLi, postedLi, detailsLi, editLi, removeLi;
ArrayAdapter<String> whenAdapter, postedAdapter, detailsAdapter,
editAdapter, removeAdapter;
ArrayAdapter<Integer> rowAdapter;
final AppointmentInfo information = new AppointmentInfo(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
/*
* The ListViews created here are not the proper way to make ListViews.
* This is for testing purposes and will be updated for efficiency. The
* remove also doesn't work properly
*/
super.onCreate(savedInstanceState);
setContentView(R.layout.manage_appointment);
initVariables();
try {
databaseManagement();
detailsLi.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> aV, View v, int pos,
long arg3) {
// TODO Auto-generated method stub
Intent openDetails = new Intent(
"com.DCWebMakers.Vairon.APPOINTMENTDETAILS");
openDetails.putExtra("position", pos);
startActivity(openDetails);
}
});
editLi.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> aV, View v, int pos,
long arg3) {
// TODO Auto-generated method stub
Intent openEdit = new Intent(
"com.DCWebMakers.Vairon.EDITAPPOINTMENT");
openEdit.putExtra("position", pos);
startActivity(openEdit);
notifyChangesToAdapters();
}
});
removeLi.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> aV, View v, int pos,
long arg3) {
// TODO Auto-generated method stub
databaseManagement();
information.open();
information.delete(pos);
information.close();
Dialog sucDeleted = new Dialog(ManageAppointment.this);
sucDeleted.setTitle("Sucesfully deleted");
TextView tvDintWorked = new TextView(ManageAppointment.this);
tvDintWorked.setText("The appointment at position:" + pos
+ " was sucesfully deleted");
sucDeleted.setContentView(tvDintWorked);
sucDeleted.show();
notifyChangesToAdapters();
}
});
} catch (Exception e) {
Dialog showError = new Dialog(this);
showError.setTitle("Error");
TextView tvDintWorked = new TextView(this);
String error = e.toString();
tvDintWorked.setText(error);
showError.setContentView(tvDintWorked);
showError.show();
}
}
public void initVariables() {
rowLi = (ListView) findViewById(R.id.rowList);
whenLi = (ListView) findViewById(R.id.whenList);
postedLi = (ListView) findViewById(R.id.postedList);
detailsLi = (ListView) findViewById(R.id.detailsList);
editLi = (ListView) findViewById(R.id.editList);
removeLi = (ListView) findViewById(R.id.removeList);
}
#Override
protected void onPause() { // TODO Auto-generated method stub
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
notifyChangesToAdapters();
}
private void notifyChangesToAdapters() {
// TODO Auto-generated method stub
rowAdapter.notifyDataSetChanged();
whenAdapter.notifyDataSetChanged();
postedAdapter.notifyDataSetChanged();
detailsAdapter.notifyDataSetChanged();
editAdapter.notifyDataSetChanged();
removeAdapter.notifyDataSetChanged();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Intent mainIntent = new Intent("com.DCWebMakers.Vairon.MAINMENU");
startActivity(mainIntent);
}
public void databaseManagement() {
information.open();
int primaryKey = information.getKeys();
String when[] = information.getWhen();
String posted[] = information.getPosted();
String details[] = new String[primaryKey];
Integer rowNumber[] = new Integer[primaryKey];
String edit[] = new String[primaryKey];
String delete[] = new String[primaryKey];
for (int set = 0; set < rowNumber.length; set++) {
rowNumber[set] = (set);
}
for (int set = 0; set < details.length; set++) {
details[set] = ("Details");
}
for (int set = 0; set < edit.length; set++) {
edit[set] = ("Edit");
}
for (int set = 0; set < delete.length; set++) {
delete[set] = ("Delete");
}
information.close();
rowAdapter = new ArrayAdapter<Integer>(ManageAppointment.this,
android.R.layout.simple_list_item_1, rowNumber);
whenAdapter = new ArrayAdapter<String>(ManageAppointment.this,
android.R.layout.simple_list_item_1, when);
postedAdapter = new ArrayAdapter<String>(ManageAppointment.this,
android.R.layout.simple_list_item_1, posted);
detailsAdapter = new ArrayAdapter<String>(ManageAppointment.this,
android.R.layout.simple_list_item_1, details);
editAdapter = new ArrayAdapter<String>(ManageAppointment.this,
android.R.layout.simple_list_item_1, edit);
removeAdapter = new ArrayAdapter<String>(ManageAppointment.this,
android.R.layout.simple_list_item_1, delete);
rowLi.setAdapter(rowAdapter);
whenLi.setAdapter(whenAdapter);
postedLi.setAdapter(postedAdapter);
detailsLi.setAdapter(detailsAdapter);
editLi.setAdapter(editAdapter);
removeLi.setAdapter(removeAdapter);
}
}
The delete method:
public void delete(int position) {
theDatabase.beginTransaction();
try {
theDatabase
.delete(DATABASE_TABLE, KEY_ROWID + "=" + position, null);
theDatabase.setTransactionSuccessful();
} catch (SQLiteException e) {
// TODO: handle exception
e.printStackTrace();
} finally {
theDatabase.endTransaction();
theDatabase.close();
}
}
before notifyDataSetChanged you need to remove the entry from the List
Did you see any exception when deleting from database. and you also need to delete pos entry from global list before notifying.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
i have problem with search, when user type something, listview will change, so the next activity will recive wrong values.
my code:
package com.example.finaltest;
import java.util.ArrayList;
import java.util.HashMap;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.text.TextWatcher;
import android.view.View;
public class Search extends ActionBarActivity {
// List view
private ListView lv;
// Listview Adapter
ArrayAdapter<String> adapter;
// Search EditText
EditText inputSearch;
// ArrayList for Listview
ArrayList<HashMap<String, String>> productList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
// Listview Data
String products[] = getResources().getStringArray(R.array.search);
lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);
// Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.subject_name, products);
lv.setAdapter(adapter);
/**
* Enabling Search Filter
* */
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// When user changed the Text
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
Search.this.adapter.getFilter().filter(arg0);
}
});
// after click
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
final String item = lv.getItemAtPosition(position).toString();
int total_number = 50;
for(int x = 1; x < total_number+1; x = x+1) {
String SubjectName = "subject_" + String.valueOf(x);
int resID = getResources().getIdentifier(SubjectName, "string", getPackageName());
String subject = getResources().getString(resID);
if(item.equals(subject)) {
String StringClass = "com.example.finaltest.Subject_" + String.valueOf(x);
Class<?> c = null;
if(StringClass != null) {
try {
c = Class.forName(StringClass);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Intent i = new Intent(getApplicationContext(), Show_Subjects.class);
String Subject_number = String.valueOf(position+1);
i.putExtra("subject_number", Subject_number);
startActivity(i);
}
}
}
});
}
#Override
public void onResume() {
super.onResume();
adapter.notifyDataSetChanged();
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_settings:
Intent delIntent = new Intent(Search.this, Settings.class);
Search.this.startActivity(delIntent);
return true;
case R.id.action_favorites:
Intent delItemIntent = new Intent(Search.this, Favorites.class);
Search.this.startActivity(delItemIntent);
return true;
}
return id == R.id.action_settings || super.onOptionsItemSelected(item);
}
}
my string names are Subject_N , i want to send values of N to next activity(from item row number)
my language is persian ,also i have an other problem, search field only support english ! change language is Inactive
//outside the for loop
ArrayList<String> ArraySubject_number = new ArrayList<String>();
String Subject_number;
//initialize your arraylist inside the loop for each row
//use something like
//for each row
Subject_number = String.valueOf(position+1);
ArraySubject_number.add(Subject_number);
//outside for loop
Intent intent= new Intent(getApplicationContext(), Show_Subjects.class);
intent.putExtras("subject_number", ArraySubject_number);
then in your other activity use this code to access them
ArrayList<String> ArraySubject_number = (ArrayList<String>) getIntent().getSerializableExtra("subject_number");
i'm using a custom ArrayAdapter to show my listView
This is my code I want to save my scroll position when go to activity and restore that when came back.
thanks
package ir.ebiroux.love;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import ir.ebiroux.database.DBAdapter;
import ir.ebiroux.database.Dastan;
import ir.ebiroux.love.R;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.annotation.SuppressLint;
import android.app.ListActivity;
import android.content.Intent;
public class MainActivity extends ListActivity {
DBAdapter db;
List<Dastan> dastanha;
ListView lst;
boolean isAll;
#SuppressLint("SdCardPath")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn_all = (Button) findViewById(R.id.main_all);
Button btn_fav = (Button) findViewById(R.id.main_fav);
isAll =true;// pish farz "All" hast
lst = getListView();
db = new DBAdapter(getBaseContext());
db.open();
Log.i(DBAdapter.TAG, "3");
dastanha = db.getAllContacts();
Log.i(DBAdapter.TAG, "4");
if (dastanha.size() == 0) {
String destPath = "/data/data/" + getPackageName() + "/databases";
try {
CopyDB(getBaseContext().getAssets().open("mydb"),
new FileOutputStream(destPath + "/dastanha"));
Log.i(DBAdapter.TAG, "db copy shod");
dastanha = db.getAllContacts();
refreshDisplay()
Log.i(DBAdapter.TAG, dastanha.size() + "= tedad dastanha");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
refreshDisplay();
}
btn_all.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
dastanha = db.getAllContacts();
isAll =true;
refreshDisplay();
}
});
btn_fav.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
dastanha = db.findFAVContacts();
isAll=false;
refreshDisplay();
}
});
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Dastan dastan = dastanha.get(position);// migim dastani ke rush kelik
Intent next = new Intent(this, ShowDastan.class);
next.putExtra("thisdastan", dastan);
startActivity(next);
}
public void CopyDB(InputStream inputStream, OutputStream outputStream)
throws IOException {
// ---copy 1K bytes at a time---
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
public void refreshDisplay() {
Log.i(DBAdapter.TAG, dastanha.size() + "= tedad dastanha");
// ye log zadim befahmim ki be kiye
ArrayAdapter<Dastan> adapter = new DastanAdapter(this, dastanha);
setListAdapter(adapter);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (isAll) {
dastanha = db.getAllContacts();
}else {
dastanha=db.findFAVContacts();
}
refreshDisplay();
}
}
You should #Override 2 more methods here. One for updating/saving the current scroll position into a variable which is "onScroll". In order for that to be triggered, add "implements OnScrollListener" to the signature of your ListActivity definition.
Then in onCreate call "getListView().setOnScrollListener(this)" to register your scroll listener.
Alternatively you can do this the same way that you did with the click listeners just dont forget to register.
Finally, override "onSaveInstanceState(Bundle yourBundle)" method of the activity and save your last updated scroll positions into the bundle.
You can then retrieve the saved scroll position in your "onCreate" method's bundle which is already there when you return to this activity. Use those positions to programmatically set the ListView's scroll position.
Ps: Sorry it's not very convenient to write any code from SO's android app but google is your friend for the missing snippets.
I get data from database (id, name) and I display (name) in a ListView. When user clicks I need to get database (id) to perform an action
KoiskesdataActivity.java
package koisk.data;
import java.util.ArrayList;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.os.StrictMode;
import android.widget.AdapterView.OnItemClickListener;
public class KoiskesdataActivity extends Activity {
/** Called when the activity is first created. */
ProgressDialog pd;
private ListView koisksListView;
private EditText myfilter;
// private ArrayAdapter <String> koiskarrayAdapter;
String koiskArray[];
Button autocompletekoisksname;
int textlength=0;
private ArrayList<String> array_sort= new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
///
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
///
koisksListView=(ListView) findViewById(R.id.koiskslist);
myfilter=(EditText) findViewById(R.id.myFilter);
///////
pd = new ProgressDialog(this);
pd.setMessage("loading...");
pd.show();
/////
getarrayofnamekoisk namekoisk=new getarrayofnamekoisk();
koiskArray=namekoisk.WW();
ArrayAdapter <String> koiskarrayAdapter=new ArrayAdapter <String>(KoiskesdataActivity.this, android.R.layout.simple_list_item_1,koiskArray);
koisksListView.setAdapter(koiskarrayAdapter);
pd.dismiss();
koisksListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
});
myfilter.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
// TODO Auto-generated method stub
textlength = myfilter.getText().length();
array_sort.clear();
for (int i = 0; i < koiskArray.length; i++)
{
if (textlength <= koiskArray[i].length())
{
//subSequence returns the specified word between the begien and end
//equalsIgnoreCase compares this String to another String, ignoring case considerations. Two strings are considered equal ignoring case if they are of the same length, and corresponding characters in the two strings are equal ignoring case
if (myfilter.getText().toString().equalsIgnoreCase((String)koiskArray[i].subSequence(0, textlength)))
{
array_sort.add(koiskArray[i]);
}
}
}
//KoiskesdataActivity.this.koiskarrayAdapter.getFilter().filter(s);
koisksListView.setAdapter(new ArrayAdapter<String>(KoiskesdataActivity.this,android.R.layout.simple_list_item_1,array_sort));
}
});
}
}
getarrayofnamekoisk.java
package koisk.data;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.xml.transform.Templates;
import android.R.array;
import android.R.integer;
import android.widget.ArrayAdapter;
import android.widget.Toast;
public class getarrayofnamekoisk{
private int i;
private String[] koiskname ;
private int num_rows;
private ArrayAdapter arrayAdapterdata;
List<String[]> names = new ArrayList<String[]>();
ArrayList<String> arr = new ArrayList<String>();
public String[] WW() {
// TODO Auto-generated method stub
connecttodatabase qq=new connecttodatabase();
qq.dbconnect();
if (qq.con !=null)
{
try
{
Statement st = qq.con.createStatement();
ResultSet rs = st.executeQuery("SELECT Name,id FROM Device where DeviceTypeId=4 and IsDeleted =0 and name is not null ");
while(rs.next())
{
arr.add(rs.getString("name"));
}
koiskname= new String [arr.size()];
arr.toArray(koiskname);
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//Toast.makeText(ConnectbyprocedureActivity.this, e.toString() , Toast.LENGTH_SHORT).show();
}
qq.closeConnection();
}
return koiskname;
}
}
connecttodatabase.java //to connect to sql server
package koisk.data;
import java.sql.DriverManager;
public class connecttodatabase {
public java.sql.Connection con = null;
private final String userName="sa";
private final String pass="123";
/////////
private final String url = "jdbc:jtds:sqlserver://";
private final String serverName= "192.168.1.200";
private final String portNumber = "1433";
private final String databaseName= "loadshedding";
////////////
/**
* #param args
*/
private String getConnectionUrl(){
//jdbc:jtds:sqlserver://192.168.1.200:1433/loadShedding
//return url+serverName+":"+portNumber+";databaseName="+databaseName+";selectMethod="+selectMethod+";";
return url+serverName+":"+portNumber+"/"+databaseName;
}
public java.sql.Connection dbconnect() {
// TODO Auto-generated method stub
try {
//Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Class.forName("net.sourceforge.jtds.jdbc.Driver");
//jdbc:jtds:sqlserver://192.168.1.200:1433/loadShedding
con = DriverManager.getConnection(getConnectionUrl(), userName, pass);
// if(con!=null) System.out.println("Connection Successful!");
}
catch(Exception e) {
e.printStackTrace();
// tv.setText(e.toString());
}
return con ;
}
// public void displayDb(){
// java.sql.DatabaseMetaData dm = null;
// java.sql.ResultSet rs = null;
// try{
// con=this.dbConnect();
// }
// catch(Exception e){
// e.printStackTrace();
// }
// }
public void closeConnection(){
try{
if(con!=null)
con.close();
con=null;
}catch(Exception e){
e.printStackTrace();
}
}
}
please i need help ..... thanks guys
You get the id from the database, but you never store it anywhere.. you first need to store it in an Array or ArrayList (lets say, idList). You have to do it similar to how you store the names in a list. then:
You can get the position of the item which is clicked inside the onItemClick method as
follows:
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
int position = arg2;
clickedID = idList.get(position);
// do something with the clicked id.
}
i got my app working so it returns the information from a json api.
now i realize that i have to put everything in a asynch task so it doesn't crash as much
and a progress dialog is easier, only i really don't know how to do this so im wondering if somebody knows a really good tutorial or wants to edit my code a bit to get my started
package net.thinkbin;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class culture extends ListActivity {
private static final String TITLE = "Title";
private static final String AUTHOR = "Author";
private static final String VIEWS = "Views";
private static final String RATES = "Rates";
private static final String CONTENT = "Content";
final Context context = this;
JSONArray ideas = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder2);
Button view = (Button) findViewById(R.id.button1);
view.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("net.thinkbin.TUTORIAL1"));
overridePendingTransition(0, 0);
finish();
}
});
Button share = (Button) findViewById(R.id.button2);
share.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("net.thinkbin.SHARE"));
overridePendingTransition(0, 0);
finish();
}
});
Button menu = (Button) findViewById(R.id.buttonhome);
menu.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.custom);
TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText("Loading...");
ImageView image = (ImageView) dialog.findViewById(R.id.image);
image.setImageResource(R.drawable.hourglass);
dialog.show();
Thread th = new Thread(new Runnable() {
public void run() {
startActivity(new Intent("net.thinkbin.MENU"));
overridePendingTransition(0, 0);
dialog.dismiss();
finish();
}
});
th.start();
}
});
ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(
this, R.array.spinnerorder,
android.R.layout.simple_spinner_item);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner s = (Spinner) findViewById(R.id.cultureorder);
s.setAdapter(adapter2);
s.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapter2, View view,
int position, long id) {
if (position == 1) {
startActivity(new Intent("net.thinkbin.CULTURE2"));
overridePendingTransition(0, 0);
finish();
}
if (position == 2) {
startActivity(new Intent("net.thinkbin.CULTURE3"));
overridePendingTransition(0, 0);
finish();
}
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
JSONObject json = JSONfunctions
.getJSONfromURL("http://www.thinkbin.net/include/api/index.php? cat=Culture&type=Newest&i=10");
try {
ideas = json.getJSONArray("Ideas");
for (int i = 0; i < ideas.length(); i++) {
JSONObject c = ideas.getJSONObject(i);
String title = c.getString(TITLE);
String author = c.getString(AUTHOR);
String views = c.getString(VIEWS);
String rates = c.getString(RATES);
String content = c.getString(CONTENT);
HashMap<String, String> map = new HashMap<String, String> ();
map.put(TITLE, "Title: " + title);
map.put(AUTHOR, "Author: " + author);
map.put(VIEWS, "Views: " + views);
map.put(RATES, "Rates: " + rates);
map.put(CONTENT, content);
mylist.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist, R.layout.main2,
new String[] { TITLE, AUTHOR, VIEWS, RATES, CONTENT },
new int[] { R.id.item_title, R.id.item_subtitle, R.id.item3,
R.id.item4, R.id.item5 });
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String Title2 = ((TextView) view.findViewById(R.id.item_title))
.getText().toString();
String Author2 = ((TextView) view
.findViewById(R.id.item_subtitle)).getText().toString();
String Content2 = ((TextView) view.findViewById(R.id.item5))
.getText().toString();
Intent in = new Intent(getApplicationContext(), idea.class);
overridePendingTransition(0, 0);
in.putExtra(TITLE, Title2);
in.putExtra(AUTHOR, Author2);
in.putExtra(CONTENT, Content2);
startActivity(in);
}
});
}
}
There is good class AsyncTask to do something Asyncronius in Android.
Example:
private class DownloadFilesTask extends AsyncTask
{
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
} }
http://developer.android.com/reference/android/os/AsyncTask.html
After following code and showing no errors when I use my button to access my list view it forces close my code is as follows
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 Listview extends ListActivity {
String classNames[] = {"home1", "Sweet", "tutorial2"};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, classNames));
}#Override
protected void onListItemClick (ListView lv, View v, int position, long id){
super.onListItemClick(lv, v, position, id);
String openClass = classNames[position];
try{
Class selected = Class.forName("us.beats.with." + openClass);
Intent selectedIntent = new Intent(this, selected);
startActivity(selectedIntent);
}catch (ClassNotFoundException e){
e.printStackTrace();
}
}
where the button was set up I had Button Listview = (Button) findViewById(R.id.Listview);
Listview.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("us.beats.with.Mylist"));
mpButtonClick.start();
but start activity was us.beats.with.Listview should have been the above
Change your classname and run it will work fine
public class MyList extends ListActivity {
String classNames[] = {"home1", "Sweet", "tutorial2"};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, classNames));
}#Override
protected void onListItemClick (ListView lv, View v, int position, long id){
super.onListItemClick(lv, v, position, id);
String openClass = classNames[position];
try{
Class selected = Class.forName("us.beats.with." + openClass);
Intent selectedIntent = new Intent(this, selected);
startActivity(selectedIntent);
}catch (ClassNotFoundException e){
e.printStackTrace();
}
}
Now run the above code