public class MainActivity extends Activity {
public static LinearLayout layout = null;
public static EditText urlstring = null;
public static Button submit = null;
public static ListView emailsfound = null;
public static ArrayList<String> emaillist = new ArrayList<String>();
public static ArrayList<String> urllist = new ArrayList<String>();
public static ArrayAdapter<String> adapter = null;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
layout = new LinearLayout(this);
urlstring = new EditText(this);
submit = new Button(this);
submit.setText("Submit");
emailsfound = new ListView(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(urlstring);
layout.addView(submit);
layout.addView(emailsfound);
setContentView(layout);
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, emaillist);
emailsfound.setAdapter(adapter);
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
urllist.add(urlstring.getText().toString());
int i = 0;
while (true) {
String page = getPage(urlstring.getText().toString());
ArrayList<String> urls = new ArrayList<String>();
urls = getURLs(page);
ArrayList<String> addresses = new ArrayList<String>();
addresses = getAddresses(page);
for (int a = 0; i < urls.size(); i++) {
urllist.add(urls.get(a));
}
for (int a = 0; a < addresses.size(); i++) {
emaillist.add(addresses.get(a));
}
removeDuplicates(urllist);
removeDuplicates(emaillist);
adapter.notifyDataSetChanged();
i++;
urlstring.setText(urllist.get(i).toString());
}
}
;
});
}
public String getPage(String url) {
if (url.toLowerCase().startsWith("http") == false) {
url = "http://" + url;
}
URL fromstring = null;
URLConnection openConnection = null;
try {
fromstring = new URL(url);
openConnection = fromstring.openConnection();
BufferedReader in = null;
url = "";
in = new BufferedReader(new InputStreamReader(openConnection.getInputStream()));
String input = "";
if (in != null) {
while ((input = in.readLine()) != null) {
url = url + input + "\r\n";
}
in.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return url;
}
public ArrayList<String> getURLs(String page) {
ArrayList<String> s = new ArrayList<String>();
while (page.toLowerCase().contains("<a href=\"http")) {
int i = page.toLowerCase().indexOf("href=\"http") + "href=\"".length();
if (i > -1) {
String s1 = page.substring(i, page.toLowerCase().indexOf("\"", i));
s.add(s1);
page = page.substring(i + "http".length());
}
}
return s;
}
public boolean validate(String email) {
Pattern pattern;
Matcher matcher;
final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*" + "#[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
pattern = Pattern.compile(EMAIL_PATTERN);
matcher = pattern.matcher(email);
return matcher.matches();
}
public ArrayList<String> getAddresses(String page) {
ArrayList<String> s = new ArrayList<String>();
while (page.contains("#")) {
int i = page.indexOf("#");
if (i > -1) {
int beginning = page.lastIndexOf(" ", i);
if (beginning > -1) {
int ending = page.indexOf(" ", i);
if (ending > -1) {
String address = page.substring(beginning + 1, ending - 1);
address = address.toLowerCase();
if (address.startsWith("href=\"mailto:")) {
int b = address.indexOf(":") + 1;
address = address.substring(b);
int e = address.indexOf("\"");
if (e > -1) {
if (e > address.indexOf("#")) {
address = address.substring(0, address.indexOf("\""));
}
if (address.contains("?")) {
address = address.substring(0, address.indexOf("?"));
}
if (!address.contains("<") && !address.contains(">")) {
if (validate(address)) {
s.add(address);
}
}
} else {
int b2 = address.indexOf(">") + 1;
if (b2 > -1) {
if (b2 < address.indexOf("#")) {
address = address.substring(b2);
}
}
int e2 = address.indexOf("<");
if (e2 > -1) {
if (e2 > address.indexOf("#")) {
address = address.substring(0, e2);
}
}
if (!address.contains("<") && !address.contains(">")) {
if (validate(address)) {
s.add(address);
}
}
}
}
}
}
}
page = page.substring(i + 1);
}
return s;
}
public ArrayList<String> removeDuplicates(ArrayList<String> List) {
ArrayList<String> output = new ArrayList<String>();
for (int i = 0; i < List.size(); i++) {
boolean b = false;
for (int a = 0; a < List.size(); i++) {
if (List.get(i).toString().toLowerCase().equals(List.get(a).toString().toLowerCase())) {
b = true;
}
}
if (b == false) {
output.add(List.get(i));
}
}
return output;
}
}
This Program Was Made in AIDE on an android netbook.
It Crashes On Button Click. I was wondering what I Was doing wrong.
I tried before with runnables but it crashed then too. I'm new to
android development but I am fluent in Java. I noticed there are
alot of differences between android and Java.
Related
i have this error in my code:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nooshindroid.yastashir/com.nooshindroid.yastashir.MainActivity}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
in dess3 and dess 4 this error has accurred!
idon't know why .but the size of dess3 and dess 4 is 0!
Route class of this code is here:
public class Route extends Activity {
String diff;
Context context;
ArrayList<String> sources, destinations, destinations2,destinations3,destinations4, answer;
public static ArrayList<Models> routeItems;
public Route(Context context) {
this.context = context;
}
public Route(String part) {
XmlPullParserFactory pullParserFactory;
try {
pullParserFactory = XmlPullParserFactory.newInstance();
XmlPullParser parser = pullParserFactory.newPullParser();
Bundle bundle = getIntent().getExtras();
diff = bundle.getString("level");
InputStream in_s = this.context.getAssets().open(diff);
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(in_s, null);
parseXML(parser);
}
catch (XmlPullParserException e) {
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void parseXML(XmlPullParser parser) throws XmlPullParserException, IOException
{
int eventType = parser.getEventType();
Models currentRout = null;
sources = new ArrayList<String>();
sources.clear();
destinations = new ArrayList<String>();
destinations.clear();
destinations2 = new ArrayList<String>();
destinations2.clear();
destinations3 = new ArrayList<String>();
destinations3.clear();
destinations4 = new ArrayList<String>();
destinations4.clear();
answer = new ArrayList<String>();
answer.clear();
while (eventType != XmlPullParser.END_DOCUMENT) {
String name = null;
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
routeItems = new ArrayList<Models>();
break;
case XmlPullParser.START_TAG:
name = parser.getName();
if (name.equalsIgnoreCase("route")) {
currentRout = new Models();
} else if (currentRout != null) {
if (name.equalsIgnoreCase("source")) {
currentRout.source = parser.nextText();
if ( !sources.contains(currentRout.source))
sources.add(currentRout.source);
} else if (name.equalsIgnoreCase("destination")) {
currentRout.destination = parser.nextText();
try {
//if ( !destinations.contains(currentRout.destination))
destinations.add(currentRout.destination);
}
catch (Exception ex)
{
}
} else if (name.equalsIgnoreCase("destination2")) {
currentRout.destination2 = parser.nextText();
try {
//if ( !destinations2.contains(currentRout.destination2))
destinations2.add(currentRout.destination2);
}
catch (Exception ex)
{
}
} else if (name.equalsIgnoreCase("destination2")) {
currentRout.destination3 = parser.nextText();
try {
//if ( !destinations2.contains(currentRout.destination2))
destinations3.add(currentRout.destination3);
}
catch (Exception ex)
{
}
} else if (name.equalsIgnoreCase("destination2")) {
currentRout.destination4 = parser.nextText();
try {
//if ( !destinations2.contains(currentRout.destination2))
destinations4.add(currentRout.destination4);
}
catch (Exception ex)
{
}
} else if (name.equalsIgnoreCase("answer")) {
currentRout.answer = parser.nextText();
try {
//if ( !destinations2.contains(currentRout.destination2))
answer.add(currentRout.answer);
}
catch (Exception ex)
{
}
}
}
break;
case XmlPullParser.END_TAG:
name = parser.getName();
if (name.equalsIgnoreCase("route") && currentRout != null) {
routeItems.add(currentRout);
}
}
eventType = parser.next();
}
}
}
main activiy of my code is as bellow:
public class MainActivity extends Activity {
public int nextque;
ArrayList<String> sourcess;
ArrayList<String> dess;
ArrayList<String> dess2;
ArrayList<String> dess3;
ArrayList<String> dess4;
ArrayList<String> answer;
int randomInt;
Random random;
Button buttons[] = new Button[8];
String j[] = new String[3];
int sumscore1 = 0;
int sumscore2 = 0;
String diff;
ProgressBar mProgressBar, mProgressBar1;
int edtTimerValue;
TextView textViewShowTime;
CountDownTimer countDownTimer;
long totalTimeCountInMilliseconds;
public void nextque() {
if ((nextque) + 1 < sourcess.size()) {
nextque++;
}
}
private void setTimer() {
int time = 0;
time = edtTimerValue;
totalTimeCountInMilliseconds = time * 1000;
mProgressBar1.setMax(time * 1000);
}
public void startTimer() {
countDownTimer = new CountDownTimer(totalTimeCountInMilliseconds, 1) {
#Override
public void onTick(long leftTimeInMilliseconds) {
long seconds = leftTimeInMilliseconds / 1000;
mProgressBar1.setProgress((int) (leftTimeInMilliseconds));
textViewShowTime.setText(String.format("%02d", seconds % 60));
}
#Override
public void onFinish() {
buttons[7].setBackgroundResource(R.drawable.blank_button);
textViewShowTime.setText("10");
textViewShowTime.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.VISIBLE);
mProgressBar1.setVisibility(View.GONE);
nextStep();
}
}.start();
}
public void nextStep() {
textViewShowTime.setVisibility(View.VISIBLE);
equation1.setVisibility(View.VISIBLE);
equation2.setVisibility(View.VISIBLE);
setTimer();
mProgressBar.setVisibility(View.INVISIBLE);
startTimer();
mProgressBar1.setVisibility(View.VISIBLE);
if(sumscore1==100){
sumscore1=0;
sumscore2=0;
score1.setText(String.valueOf(sumscore1));
score2.setText(String.valueOf(sumscore2));
}
if (sumscore2==100){
sumscore1=0;
sumscore2=0;
score1.setText(String.valueOf(sumscore1));
score2.setText(String.valueOf(sumscore2));
}
random = new Random();
randomInt = random.nextInt(sourcess.size());
equation1.setText(sourcess.get(nextque));
equation2.setText(sourcess.get(nextque));
Random rn = new Random();
int index = rn.nextInt(3) + 0;
Log.e("rand poduct", String.valueOf(index));
nextque();
equation1 = (TextView) findViewById(R.id.equation1);
buttons[index].setText( answer.get(nextque));
dess.size();
int k = 0;
for (int i = 0; i <= 3; i++) {
Log.e("prod", "loop " + i);
if (i != index ) {
if(!(answer.get(nextque).equals(j[k]))){
buttons[i].setText((j[k]));
}
k++;
}
}
equation2 = (TextView) findViewById(R.id.equation2);
Random rt = new Random();
int index2 = rt.nextInt(3) + 0;
int index3 = index2 + 4;
buttons[index3].setText( answer.get(nextque));
int d = 0;
for (int i = 4; i <= 7; i++) {
if (i != index3) {
if(!(answer.get(nextque).equals(j[d]))){
buttons[i].setText((j[d]));
}
d++;
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
equal1 = (TextView) findViewById(R.id.equal1);
equal2 = (TextView) findViewById(R.id.equal2);
bord1 = (TextView) findViewById(R.id.bord1);
bord2 = (TextView) findViewById(R.id.bord2);
bakht1 = (TextView) findViewById(R.id.bakht1);
bakht2 = (TextView) findViewById(R.id.bakht2);
refreash = (ImageView) findViewById(R.id.refreash);
textViewShowTime = (TextView) findViewById(R.id.textView_timerview_time);
edtTimerValue = 10;
mProgressBar = (ProgressBar) findViewById(R.id.progressbar_timerview);
mProgressBar1 = (ProgressBar) findViewById(R.id.progressbar1_timerview);
Bundle bundle = getIntent().getExtras();
Typeface font = Typeface.createFromAsset(getAssets(), "BYekan.ttf");
diff = bundle.getString("level");
textViewShowTime.setTypeface(font);
route = new Route(getApplicationContext());
XmlPullParserFactory pullParserFactory;
try {
pullParserFactory = XmlPullParserFactory.newInstance();
XmlPullParser parser = pullParserFactory.newPullParser();
InputStream in_s = getApplicationContext().getAssets().open("easys.xml");
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(in_s, null);
route.parseXML(parser);
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sourcess = new ArrayList<String>();
for (int i = 0; i < route.sources.size(); i++) {
sourcess.add(i, route.sources.get(i));
}
dess = new ArrayList<String>();
for (int i = 0; i < route.destinations.size(); i++) {
dess.add(i, route.destinations.get(i));
}
dess2 = new ArrayList<String>();
for (int i = 0; i < route.destinations2.size(); i++) {
dess2.add(i, route.destinations2.get(i));
}
dess3 = new ArrayList<String>();
for (int i = 0; i < route.destinations3.size(); i++) {
dess3.add(i, route.destinations3.get(i));
}
dess4 = new ArrayList<String>();
for (int i = 0; i < route.destinations4.size(); i++) {
dess4.add(i, route.destinations4.get(i));
}
answer = new ArrayList<String>();
for (int i = 0; i < route.answer.size(); i++) {
answer.add(i, route.answer.get(i));
}
nextStep();
}
}
can anyone help me to solve it?thank alot for your attention.
The array size of array j is 3. But when you are using it inside the loop, you are iterating it more than its size.. Try increasing the size of the arrays and check.
Along with the error you get the line number too of the error, post it if possible.
plz help me
I did added async library at my project and checked already, I don't know why code flow doesn't go in to asynctask
my Update code doesn't execute.
in this line my update calss doesnt run
dataupdate.execute();
CODE:
public class Update extends AsyncTask<Void, Void, Integer> {
private String User;
private final String mLink;
public Update(String user) {
User = user;
mLink = "http://www./Update.php";
}
#Override
protected Integer doInBackground(Void... params) {
try {
String data = URLEncoder.encode("username", "UTF8") + "=" + URLEncoder.encode(User, "UTF8");
URL mylink = new URL(mLink);
URLConnection connect = mylink.openConnection();
connect.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(connect.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
int f = 0, w = 0, C = 0;
String name = null;
String status = null;
Integer money = null;
boolean isDebtor = false;
boolean isCreditor = false;
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) == '|') {
if (w == 1) {
String temp2 = line.substring(f, i);
if (!temp2.equals(User)) {
isDebtor = true;
name = temp2;
}
} else if (w == 2) {
String temp2 = line.substring(f, i);
if (!temp2.equals(User)) {
isCreditor = true;
name = temp2;
}
} else if (w == 3) {
String temp2 = line.substring(f, i);
money = Integer.parseInt(temp2);
} else if (w == 4) {
String temp2 = line.substring(f, i);
status = temp2;
}
f = i + 1;
w++;
}
}
Pair<String, Pair<Integer, String>> temp = new Pair<>(name, new Pair<>(money, status));
if (isDebtor) {
MainActivity.Debtor.add(temp);
}
if (isCreditor) {
MainActivity.Creditor.add(temp);
}
}
} catch (Exception e) {
}
return null;
}
}
Main:
showProgress(true);
dataupdate = new Update(username);
dataupdate.execute();
// dataupdate.execute((Void) null);
showProgress(false);
do it like this
public class Update extends AsyncTask<String, String, Integer> {
#Override
protected Integer doInBackground(String... params) {
User user=params[0]; //get string user value here
try {
String data = URLEncoder.encode("username", "UTF8") + "=" + URLEncoder.encode(user, "UTF8");
URL mylink = new URL(mLink);
URLConnection connect = mylink.openConnection();
connect.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(connect.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
int f = 0, w = 0, C = 0;
String name = null;
String status = null;
Integer money = null;
boolean isDebtor = false;
boolean isCreditor = false;
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) == '|') {
if (w == 1) {
String temp2 = line.substring(f, i);
if (!temp2.equals(User)) {
isDebtor = true;
name = temp2;
}
} else if (w == 2) {
String temp2 = line.substring(f, i);
if (!temp2.equals(User)) {
isCreditor = true;
name = temp2;
}
} else if (w == 3) {
String temp2 = line.substring(f, i);
money = Integer.parseInt(temp2);
} else if (w == 4) {
String temp2 = line.substring(f, i);
status = temp2;
}
f = i + 1;
w++;
}
}
Pair<String, Pair<Integer, String>> temp = new Pair<>(name, new Pair<>(money, status));
if (isDebtor) {
MainActivity.Debtor.add(temp);
}
if (isCreditor) {
MainActivity.Creditor.add(temp);
}
}
} catch (Exception e) {
e.printstacktrace();
}
return null;
}
}
to run
//put username value in execute
new Update()execute(username);
I'm now currently working on a project that lets the user view the list of a certain table and has the privilege of either editing or deleting it. There's no error, I just don't have any idea on what to do. Maybe anyone could help me on even just the delete feature? Giving a sample code would be so much helpful. Here's my code:
SQLiteDatabase myDataBase;
String DB_PATH = null;
private ProgressDialog m_ProgressDialog = null;
private ArrayList<Order> m_orders = null;
private OrderAdapter m_adapter;
private Runnable viewOrders;
int totalId, totalProdId, totalQty, totalBigQty, totalUnitQty;
Cursor cursorProduct;
String id = "";
String productid = "";
String qty = "";
String bigqty = "";
String unitqty = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dc_invviewlist);
copyDB();
myDataBase = SQLiteDatabase.openOrCreateDatabase(DB_PATH,null);
m_orders = new ArrayList<Order>();
this.m_adapter = new OrderAdapter(this, R.layout.dc_inventory_viewlist, m_orders);
setListAdapter(this.m_adapter);
viewOrders = new Runnable(){
#Override
public void run() {
getOrders();
}
};
Thread thread = new Thread(null, viewOrders, "MagentoBackground");
thread.start();
m_ProgressDialog = ProgressDialog.show(DC_invviewlist.this,
"Please wait...", "Retrieving data ...", true);
registerForContextMenu(getListView());
}
private Runnable returnRes = new Runnable() {
#Override
public void run() {
if(m_orders != null && m_orders.size() > 0){
m_adapter.notifyDataSetChanged();
for(int i=0;i<m_orders.size();i++)
m_adapter.add(m_orders.get(i));
}
m_ProgressDialog.dismiss();
m_adapter.notifyDataSetChanged();
}
};
private void getOrders(){
try{
String i = getPIViewListId();
String pi = getPIViewListProdId();
String q = getPIViewListQty();
String bq = getPIViewListBigQty();
String uq = getPIViewListUnitQty();
String[] iValue = i.split("~");
String[] piValue = pi.split("~");
String[] qValue = q.split("~");
String[] bqValue = bq.split("~");
String[] uqValue = uq.split("~");
totalId = iValue.length;
totalProdId = piValue.length;
totalQty = qValue.length;
totalBigQty = bqValue.length;
totalUnitQty = uqValue.length;
m_orders = new ArrayList<Order>();
for (int j = 0; j < totalId; j++) {
Order o = new Order();
o.setOrderId(iValue[j]);
o.setOrderProdId(piValue[j]);
o.setOrderQty(qValue[j]);
o.setOrderBigQty(bqValue[j]);
o.setOrderUnitQty(uqValue[j]);
m_orders.add(o);
}
Thread.sleep(2000);
Log.i("ARRAY", ""+ m_orders.size());
} catch (Exception e) {
Log.e("BACKGROUND_PROC", e.getMessage());
}
runOnUiThread(returnRes);
}
private class OrderAdapter extends ArrayAdapter<Order> {
private ArrayList<Order> items;
public OrderAdapter(Context context, int textViewResourceId, ArrayList<Order> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.dc_inventory_viewlist, null);
}
Order o = items.get(position);
if (o != null) {
TextView id = (TextView) v.findViewById(R.id.txtInvViewListId);
TextView prodid = (TextView) v.findViewById(R.id.txtInvViewListProductId);
TextView qty = (TextView) v.findViewById(R.id.txtInvViewListQty);
TextView bigqty = (TextView) v.findViewById(R.id.txtInvViewListBigQty);
TextView unitqty = (TextView) v.findViewById(R.id.txtInvViewListUnitQty);
if (id != null) {
id.setText(o.getOrderId()); }
if(prodid != null){
prodid.setText(o.getOrderProdId());
}
if(qty != null){
qty.setText(o.getOrderQty());
}
if(bigqty != null){
bigqty.setText(o.getOrderBigQty());
}
if(unitqty != null){
unitqty.setText(o.getOrderUnitQty());
}
}
return v;
}
}
public void copyDB(){
if(android.os.Build.VERSION.SDK_INT >= 17){
DB_PATH = getApplicationContext().getApplicationInfo().dataDir + "/databases/";
}
else{
DB_PATH = "/data/data/" + getApplicationContext().getPackageName() + "/databases/";
}
File dbdir = new File(DB_PATH);
if(!dbdir.exists()){
dbdir.mkdirs();
}
File file = new File(DB_PATH+"DC");
if(!file.exists()){
try{
InputStream is = getApplicationContext().getAssets().open("DC");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
FileOutputStream fos = new FileOutputStream(file);
fos.write(buffer);
fos.flush();
fos.close();
}catch(Exception e){ throw new RuntimeException(e);};
}
if(android.os.Build.VERSION.SDK_INT >= 17){
DB_PATH = getApplicationInfo().dataDir + "/databases/DC";
}else{
DB_PATH = "/data/data/" + getPackageName() + "/databases/DC";
}
}
#Override
protected void onResume() {
super.onResume();
myDataBase = SQLiteDatabase.openOrCreateDatabase(DB_PATH, null);
}
#Override
protected void onPause() {
super.onPause();
myDataBase.close();
}
public String getPIViewListId(){
cursorProduct = myDataBase.rawQuery("Select * from tblProductInvAdjust", null);
if (cursorProduct.moveToFirst()) {
do {
id += ""+cursorProduct.getString(0)+"~";
} while (cursorProduct.moveToNext());
}
if (cursorProduct != null && !cursorProduct.isClosed()) {
cursorProduct.close();
}
return id;
}
public String getPIViewListProdId(){
cursorProduct = myDataBase.rawQuery("Select * from tblProductInvAdjust", null);
if (cursorProduct.moveToFirst()) {
do {
productid += ""+cursorProduct.getString(1)+"~";
} while (cursorProduct.moveToNext());
}
if (cursorProduct != null && !cursorProduct.isClosed()) {
cursorProduct.close();
}
return productid;
}
public String getPIViewListQty(){
cursorProduct = myDataBase.rawQuery("Select * from tblProductInvAdjust", null);
if (cursorProduct.moveToFirst()) {
do {
qty += ""+cursorProduct.getString(2)+"~";
} while (cursorProduct.moveToNext());
}
if (cursorProduct != null && !cursorProduct.isClosed()) {
cursorProduct.close();
}
return qty;
}
public String getPIViewListBigQty(){
cursorProduct = myDataBase.rawQuery("Select * from tblProductInvAdjust", null);
if (cursorProduct.moveToFirst()) {
do {
bigqty += ""+cursorProduct.getString(3)+"~";
} while (cursorProduct.moveToNext());
}
if (cursorProduct != null && !cursorProduct.isClosed()) {
cursorProduct.close();
}
return bigqty;
}
public String getPIViewListUnitQty(){
cursorProduct = myDataBase.rawQuery("Select * from tblProductInvAdjust", null);
if (cursorProduct.moveToFirst()) {
do {
unitqty += ""+cursorProduct.getString(4)+"~";
} while (cursorProduct.moveToNext());
}
if (cursorProduct != null && !cursorProduct.isClosed()) {
cursorProduct.close();
}
return unitqty;
}
final int CONTEXT_MENU_EDIT_ITEM =1;
final int CONTEXT_MENU_DELETE =2;
#Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenu.ContextMenuInfo menuInfo) {
menu.add(Menu.NONE, CONTEXT_MENU_EDIT_ITEM, Menu.NONE, "Edit");
menu.add(Menu.NONE, CONTEXT_MENU_DELETE, Menu.NONE, "Delete");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
Long id = getListAdapter().getItemId(info.position);
switch (item.getItemId()) {
case CONTEXT_MENU_EDIT_ITEM:
//do smth
return(true);
case CONTEXT_MENU_DELETE:
myDataBase.execSQL("DELETE FROM tblProductInvAdjust");
return(true);
}
return(super.onOptionsItemSelected(item));
}
I hope anyone could help me on this. I really need a help right now. Thanks! :)
You can use this
sql_lite_db_obj.delete(tablename, whereClause, whereArgs)
For your convenience i edited my answer
public void clickHandler(View v) {
if (v.getId() == R.id.deleteOrder) {
int _id = 0;
try {
_id = (Integer) v.getTag(R.id.orderTitle);
} catch (Exception e) {
e.printStackTrace();
}
dh.delete(DatabaseHelpere.TableNAME, "_id=?",new String[] { String.valueOf(_id) });
}
}
I write one function for get data from database.
I have set a breakpoint and make sure the function is already get data for return
but when I use the function I Can't get data back in My main function
is my data structure error? or other thing error?
thanks for your help.
import java.util.ArrayList;
public class ScheduleData {
public String strID;
public String strName;
public String strDesc;
public Integer iScheduleDay;
public String strStartDate;
public ArrayList<ScheduleContent> alPOI;
public ScheduleData() {
strID = new String();
strName = new String();
strDesc = new String();
strStartDate = new String();
iScheduleDay = 0;
alPOI = new ArrayList<ScheduleContent>();
}
}
//
public class ScheduleContent {
public String strPOIID;
public int iSequence ;
public int iDay ;
public String strTime;
public int iStayTime ;
public ScheduleContent() {
iSequence = 1;
iDay = 1;
iStayTime = 0;
}
}
//
public boolean bInitData() {
ArrayList<ScheduleData> alEx = alGetAllSchedule();
}
private ArrayList<ScheduleData> alGetAllSchedule() {
ArrayList<ScheduleData> alTmp = new ArrayList<ScheduleData>();
try {
mDATA.m_alAllSchedule.clear();
Cursor c = objSchedule.getAllCursor();
ScheduleDataInit();
if (c.getCount() > 0) {
if (c.moveToFirst()) {
while (c.isAfterLast() == false) {
ScheduleData sTmp = new ScheduleData();
sTmp.strID = c.getString(c.getColumnIndex("SID"));
sTmp.strName = c.getString(c.getColumnIndex("S_Name"));
sTmp.strDesc = c.getString(c.getColumnIndex("S_Desc"));
sTmp.strStartDate = c.getString(c
.getColumnIndex("S_StartDate"));
sTmp.iScheduleDay = Integer.valueOf(c.getInt(c
.getColumnIndex("S_Day")));
sTmp.alPOI=mDATA.m_hAllScheduleContent.get(sTmp.strID);
alTmp.add(sTmp);
c.moveToNext();
}
}
}
mDATA.m_alAllSchedule = alTmp;
c.close();
} catch (Exception errMsg) {
errMsg.printStackTrace();
}
return alTmp;
}
public class master extends Activity {
ProgressDialog progressDialog;
EditText tahmini_kelime;
EditText girilen_sayi ;
EditText toplam_harf_sayisi ;
Button tamamdir;
TextView jTextArea1;
Vector vector_all,vect_end,vect,recent_search;
BufferedReader read;
String recent_tahmin_kelime;
boolean bayrak,bayrak2 ;
int column_number ;
InputStreamReader inputreader ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.master);
column_number=0;
bayrak=true;
toplam_harf_sayisi=(EditText)findViewById(R.id.toplam_harf);
tahmini_kelime=(EditText)findViewById(R.id.tahmini_kelime);
girilen_sayi=(EditText)findViewById(R.id.sayi_gir);
tamamdir=(Button)findViewById(R.id.tamamdirrrr);
jTextArea1=(TextView)findViewById(R.id.jte);
bayrak2=true;
recent_search = new Vector();
InputStream inputStream = getResources().openRawResource(R.raw.sozluk);
try {
inputreader = new InputStreamReader(inputStream,"utf-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
};
read = new BufferedReader(inputreader);
int k = 0;
String result = "";
try {
vector_all = new Vector();
while (read.ready()) {
result = read.readLine();
vector_all.add(result);
jTextArea1.append(result + "\n");
k = k + 1;
}
String size = "" + k;
} catch (IOException ex) {
}
tamamdir.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if( bayrak2 )
{
if(Integer.parseInt(toplam_harf_sayisi.getText().toString())>8 || Integer.parseInt(toplam_harf_sayisi.getText().toString())<=1)
{
toplam_harf_sayisi.setText("");
Dialog dl=new Dialog(master.this);
dl.setTitle("hatalı giriş");
dl.setCanceledOnTouchOutside(true);
dl.show();
return;
}
int findwordlength = Integer.parseInt(toplam_harf_sayisi.getText().toString());
int k = 0;
String result = "";
jTextArea1.setText("");
InputStream inputStream = getResources().openRawResource(R.raw.sozluk);
try {
inputreader = new InputStreamReader(inputStream,"utf-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
};
read = new BufferedReader(inputreader);
String resultword = "";
try {
vect = new Vector();
while (read.ready()) {
result = read.readLine();
if (result.length() == findwordlength) {
vect.addElement(result);
resultword = resultword + result + "\n";
k = k + 1;
}
jTextArea1.setText("");
}
jTextArea1.append(resultword + "\n");
RandomKelime(vector_all,0 );
} catch (IOException ex) {
}
toplam_harf_sayisi.setEnabled(false);
girilen_sayi.setEnabled(true);
bayrak2=false;
}
else
{
progressDialog = ProgressDialog.show(master.this, "Bir Düşüneyim :D", "lütfen bekleyiniz...");
Thread thread = new Thread(new Runnable() {
public void run() {
mainGuessWord(column_number);
handler.sendEmptyMessage(0);
}
});
thread.start();
girilen_sayi.setText("");
}
}
});
}
private void mainGuessWord(int look) {
int result_int = 0;
String randomword = "";
int randomword2 = 0;
randomword = tahmini_kelime.getText().toString();
result_int = Integer.parseInt(girilen_sayi.getText().toString());
if (result_int == 0) {
mevcut_degil(vect, randomword);
} else {
elemeAgaci(vect, randomword, result_int);
}
}
public void elemeAgaci(Vector vect, String elem, int length) {
String word = elem.toString();
Vector cmp_vect;
cmp_vect = new Vector();
vect_end = new Vector();
int count = 0;
int countword = 0; // toplam word sayısı
int each_word_total = 0; // her kelimede bulunan harf sayısı
jTextArea1.setText("");
String compare = "";
for (int i = 0; i < vect.size(); i++) {
each_word_total = 0;
compare = "";
for (int j = 0; j < word.length(); j++) {
if(!compare.contains(""+word.charAt(j)))
{
for (int k = 0; k < vect.get(i).toString().length(); k++) {
if (vect.get(i).toString().charAt(k) == word.charAt(j)) {
each_word_total++;
}
}
compare=""+compare+word.charAt(j);
}
}
System.out.println("" + vect.get(i) + " => " + each_word_total);
if (length == each_word_total) {
cmp_vect.add(vect.get(i));
jTextArea1.append(vect.get(i) + "\n");
countword++;
}
}
vect.clear();
for (int l = 0; l < cmp_vect.size(); l++) {
vect.add(cmp_vect.get(l));
}
if (countword == 1) {
Dialog dl=new Dialog(master.this);
dl.setTitle("The Word id : "+jTextArea1.getText().toString());
dl.setCanceledOnTouchOutside(true);
dl.show();
} else {
column_number = column_number + 1;
if(vect.size()<10){
RandomKelime_Table(vect);
}else{
RandomKelime(vector_all, column_number);
}
}
}
public void mevcut_degil(Vector vect, String m) {
char control[];
control = m.toCharArray();
boolean flag = false;
int countword = 0;
Vector detect;
detect = new Vector();
jTextArea1.setText("");
for (int k = 0; k < vect.size(); k++) {
flag = false;
for (int s = 0; s < control.length; s++) {
if (vect.get(k).toString().contains("" + control[s])) {
flag = true;
}
}
if (!flag) {
detect.addElement(vect.get(k));
countword = countword + 1;
}
}
vect.clear();
for (int s = 0; s < detect.size(); s++) {
vect.addElement(detect.get(s));
}
for (int a = 0; a < countword; a++) {
jTextArea1.append(vect.get(a).toString() + "\n");
}
if (countword == 1) {
Dialog dl=new Dialog(master.this);
dl.setTitle("The Word id : "+jTextArea1.getText().toString());
dl.setCanceledOnTouchOutside(true);
dl.show();
}
else {
column_number = column_number + 1;
RandomKelime(vect, column_number);
}
}
public void RandomKelime(Vector vector, int k)
{
String sesli[]={"a","e","ı","i","o","ö","u","ü"};
Random a = new Random();
if (k == 0) {
String passedword = "";
passedword = vector_all.get((int) (Math.random() * vector_all.size())).toString();
while (passedword.length() < 8) {
passedword = vector_all.get((int) (Math.random() * vector_all.size())).toString();
}
tahmini_kelime.setText(passedword);
recent_tahmin_kelime=passedword;
// jTable1.setValueAt(vector_all.get((int) (Math.random() * vector_all.size())), k, 0);
} else {
recent_search.addElement(recent_tahmin_kelime );
int say = 0;
String design = "";
String guess_words = "";
String as="";
int f=0;
int count=0;
int calculate_all=0;
for (int u = 0; u < recent_search.size(); u++) {
design = recent_search.get(u).toString();
bayrak = false;
as="";
count=0;
for(int s=0;s<sesli.length;s++)
{
if(design.contains(""+sesli[s]) && count==0){
as+=""+sesli[s];
count++;
}
}
guess_words = vector_all.get((int) a.nextInt(vector_all.size())).toString();
while (guess_words.length() < 8) {
guess_words = vector_all.get((int) (Math.random() * vector_all.size())).toString();
}
while (say < design.length()) {
calculate_all=0;
while (guess_words.contains("" + as) && !design.equals(guess_words)) {
say = 0;
calculate_all++;
guess_words = vector_all.get( a.nextInt(vector_all.size())).toString();
while (guess_words.length() < 8) {
guess_words = vector_all.get((int) (Math.random() * vector_all.size())).toString();
}
f=f+1;
System.out.println("Tahmın: " + guess_words + " => " + design);
if(calculate_all>vect.size())
{
break;
}
}
say++;
System.out.println("coutn: " + say);
}
}
if (true) {
tahmini_kelime.setText(guess_words);
}
}
}
public void RandomKelime_Table(Vector vector ) {
String passedword = "";
Random a = new Random();
try {
passedword = vect.get(a.nextInt(vect.size())).toString();
} catch (Exception e) {
Dialog dl=new Dialog(master.this);
dl.setTitle("Hatalı Giriş.Yeniden Başlayın.");
dl.setCanceledOnTouchOutside(true);
dl.show();
yeniden_basla();
}
tahmini_kelime.setText(passedword );
}
public void yeniden_basla()
{
bayrak2=true;
girilen_sayi.setEnabled(false);
toplam_harf_sayisi.setEnabled(true);
toplam_harf_sayisi.setText("");
vect.clear();
vector_all.clear();
vect_end.clear();
recent_search.clear();
jTextArea1.setText("");
recent_tahmin_kelime="";
column_number=0;
bayrak=true;
InputStream inputStream = getResources().openRawResource(R.raw.sozluk);
try {
inputreader = new InputStreamReader(inputStream,"utf-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
};
read = new BufferedReader(inputreader);
int k = 0;
String result = "";
try {
vector_all = new Vector();
while (read.ready()) {
result = read.readLine();
vector_all.add(result);
jTextArea1.append(result + "\n");
k = k + 1;
}
String size = "" + k;
} catch (IOException ex) {
}
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
progressDialog.dismiss();
}
};
}
this all of my code.
You don't show where you create your handler (onCreate ? onStart ? somewhere else ?). Is it started from the main thread ? If so, you need to be provide a more complete stack trace so we can understand.
If you're starting it from another thread then that's the issue because it's attempting to change progressDialog and that must be done from the main thread.
PS: if you used an AsyncTask you wouldn't have to scratch your head around this as it's designed to do exactly what you want and be thread safe.
Post comment : use an AsyncThread : add the progress bar in onPreExecute(), change run() to doInBackground() and move the dismiss() to onPostExecute(