Search Results

Search found 383 results on 16 pages for 'toast'.

Page 6/16 | < Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • Forced closed only when put alphabetical string in edit text

    - by Abdullah Al Mubarok
    So, I make a checker if an id is in the database or not, the id is in numerical string, the type in database is char(6) though. So this is my code public class input extends Activity{ /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.input); final EditText edittext = (EditText)findViewById(R.id.editText1); Button button = (Button)findViewById(R.id.button1); button.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { // TODO Auto-generated method stub String nopel = edittext.getText().toString(); if(nopel.length() == 0){ Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show(); }else{ List<NameValuePair> pairs = new ArrayList<NameValuePair>(); pairs.add(new BasicNameValuePair("nopel", nopel)); JSON json_dp = new JSON(); JSONObject jobj_dp = json_dp.getJSON("http://10.0.2.2/KP/pdam/nopel.php", pairs); try { if(jobj_dp.getInt("row") == 0){ Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show(); }else{ String snopel = jobj_dp.getString("nopel"); String snama = jobj_dp.getString("nama"); String salamat = jobj_dp.getString("alamat"); String sgolongan = jobj_dp.getString("golongan"); Intent i = new Intent(input.this, list.class); i.putExtra("nopel", snopel); i.putExtra("nama", snama); i.putExtra("alamat", salamat); i.putExtra("golongan", sgolongan); startActivity(i); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }); } } the first check is to check if an input is null, it's going right for now, the second check is to check if an id in the database, and it's the problem. When I try some id in numerical value like "0001" or "02013" it's fine, and can run. but when I just got to put "abushd" it forced close. anyone know why I got this?

    Read the article

  • Performance issues in android game

    - by user1446632
    I am making an android game, but however, the game is functioning like it should, but i am experiencing some performance issues. I think it has something to do with the sound. Cause each time i touch the screen, it makes a sound. I am using the standard MediaPlayer. The method is onTouchEvent() and onPlaySound1(). Could you please help me with an alternate solution for playing the sound? Thank you so much in advance! It would be nice if you also came up with some suggestions on how i can improve my code. Take a look at my code here: package com.mycompany.mygame; import java.util.ArrayList; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.media.MediaPlayer; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.webkit.WebView; import android.widget.TextView; import android.widget.Toast; public class ExampleView extends SurfaceView implements SurfaceHolder.Callback { class ExampleThread extends Thread { private ArrayList<Parachuter> parachuters; private Bitmap parachuter; private Bitmap background; private Paint black; private boolean running; private SurfaceHolder mSurfaceHolder; private Context mContext; private Context mContext1; private Handler mHandler; private Handler mHandler1; private GameScreenActivity mActivity; private long frameRate; private boolean loading; public float x; public float y; public float x1; public float y1; public MediaPlayer mp1; public MediaPlayer mp2; public int parachuterIndexToResetAndDelete; public int canvasGetWidth; public int canvasGetWidth1; public int canvasGetHeight; public int livesLeftValue; public int levelValue = 1; public int levelValue1; public int parachutersDown; public int difficultySet; public boolean isSpecialAttackAvailible; public ExampleThread(SurfaceHolder sHolder, Context context, Handler handler) { mSurfaceHolder = sHolder; mHandler = handler; mHandler1 = handler; mContext = context; mActivity = (GameScreenActivity) context; parachuters = new ArrayList<Parachuter>(); parachuter = BitmapFactory.decodeResource(getResources(), R.drawable.parachuteman); black = new Paint(); black.setStyle(Paint.Style.FILL); black.setColor(Color.GRAY); background = BitmapFactory.decodeResource(getResources(), R.drawable.gamescreenbackground); running = true; // This equates to 26 frames per second. frameRate = (long) (1000 / 26); loading = true; mp1 = MediaPlayer.create(getContext(), R.raw.bombsound); } @Override public void run() { while (running) { Canvas c = null; try { c = mSurfaceHolder.lockCanvas(); synchronized (mSurfaceHolder) { long start = System.currentTimeMillis(); doDraw(c); long diff = System.currentTimeMillis() - start; if (diff < frameRate) Thread.sleep(frameRate - diff); } } catch (InterruptedException e) { } finally { if (c != null) { mSurfaceHolder.unlockCanvasAndPost(c); } } } } protected void doDraw(Canvas canvas) { canvas.drawRect(0, 0, canvas.getWidth(), canvas.getHeight(), black); //Draw for (int i = 0; i < parachuters.size(); i++) { canvas.drawBitmap(parachuter, parachuters.get(i).getX(), parachuters.get(i).getY(), null); parachuters.get(i).tick(); } //Remove for (int i = 0; i < parachuters.size(); i++) { if (parachuters.get(i).getY() > canvas.getHeight()) { parachuters.remove(i); onPlaySound(); checkLivesLeftValue(); checkAmountOfParachuters(); } else if(parachuters.get(i).isTouched()) { parachuters.remove(i); } else{ //Do nothing } } } public void loadBackground(Canvas canvas) { //Load background canvas.drawBitmap(background, 0, 0, black); } public void checkAmountOfParachuters() { mHandler.post(new Runnable() { @Override public void run() { if(parachuters.isEmpty()) { levelValue = levelValue + 1; Toast.makeText(getContext(), "New level! " + levelValue, 15).show(); if (levelValue == 3) { drawParachutersGroup1(); drawParachutersGroup2(); drawParachutersGroup3(); drawParachutersGroup4(); } else if (levelValue == 5) { drawParachutersGroup1(); drawParachutersGroup2(); drawParachutersGroup3(); drawParachutersGroup4(); drawParachutersGroup5(); } else if (levelValue == 7) { drawParachutersGroup1(); drawParachutersGroup2(); drawParachutersGroup3(); drawParachutersGroup4(); drawParachutersGroup5(); drawParachutersGroup6(); } else if (levelValue == 9) { //Draw 7 groups of parachuters drawParachutersGroup1(); drawParachutersGroup2(); drawParachutersGroup3(); drawParachutersGroup4(); drawParachutersGroup5(); drawParachutersGroup6(); drawParachutersGroup1(); } else if (levelValue > 9) { //Draw 7 groups of parachuters drawParachutersGroup1(); drawParachutersGroup2(); drawParachutersGroup3(); drawParachutersGroup4(); drawParachutersGroup5(); drawParachutersGroup6(); drawParachutersGroup1(); } else { //Draw normal 3 groups of parachuters drawParachutersGroup1(); drawParachutersGroup2(); drawParachutersGroup3(); } } else { //Do nothing } } }); } private void checkLivesLeftValue() { mHandler.post(new Runnable() { @Override public void run() { Log.d("checkLivesLeftValue", "lives = " + livesLeftValue); // TODO Auto-generated method stub if (livesLeftValue == 3) { //Message to display: "You lost! Log.d("checkLivesLeftValue", "calling onMethod now"); parachuters.removeAll(parachuters); onMethod(); } else if (livesLeftValue == 2) { Toast.makeText(getContext(), "Lives left=1", 15).show(); livesLeftValue = livesLeftValue + 1; Log.d("checkLivesLeftValue", "increased lives to " + livesLeftValue); } else if (livesLeftValue == 1) { Toast.makeText(getContext(), "Lives left=2", 15).show(); livesLeftValue = livesLeftValue + 1; Log.d("checkLivesLeftValue", "increased lives to " + livesLeftValue); } else { //Set livesLeftValueText 3 Toast.makeText(getContext(), "Lives left=3", 15).show(); livesLeftValue = livesLeftValue + 1; Log.d("checkLivesLeftValue", "increased lives to " + livesLeftValue); } } }); } public void onMethod() { mHandler.post(new Runnable() { @Override public void run() { try { Toast.makeText(getContext(), "You lost!", 15).show(); livesLeftValue = 0; //Tell the user that he lost: android.content.Context ctx = mContext; Intent i = new Intent(ctx, playerLostMessageActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.putExtra("KEY","You got to level " + levelValue + " And you shot down " + parachutersDown + " parachuters"); i.putExtra("levelValue", levelValue); ctx.startActivity(i); System.exit(0); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); //Exit activity and start playerLostMessageActivity Toast.makeText(getContext(), "You lost!", 15).show(); livesLeftValue = 0; //Tell the user that he lost: android.content.Context ctx = mContext; Intent i = new Intent(ctx, playerLostMessageActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.putExtra("KEY","You got to level " + levelValue + " And you shot down " + parachutersDown + " parachuters"); i.putExtra("levelValue", levelValue); System.exit(0); ctx.startActivity(i); System.exit(0); } } }); } public void onPlaySound() { try { mp1.start(); } catch (Exception e) { e.printStackTrace(); mp1.release(); } } public void onDestroy() { try { parachuters.removeAll(parachuters); mp1.stop(); mp1.release(); } catch (Exception e) { e.printStackTrace(); } } public void onPlaySound1() { try { mp2 = MediaPlayer.create(getContext(), R.raw.airriflesoundeffect); mp2.start(); } catch (Exception e) { e.printStackTrace(); mp2.release(); } } public boolean onTouchEvent(MotionEvent event) { if (event.getAction() != MotionEvent.ACTION_DOWN) releaseMediaPlayer(); x1 = event.getX(); y1 = event.getY(); checkAmountOfParachuters(); removeParachuter(); return false; } public void releaseMediaPlayer() { try { mp1.release(); } catch (Exception e) { e.printStackTrace(); } } public void removeParachuter() { try { for (Parachuter p: parachuters) { if (x1 > p.getX() && x1 < p.getX() + parachuter.getWidth() && y1 > p.getY() && y1 < p.getY() + parachuter.getHeight()) { p.setTouched(true); onPlaySound1(); parachutersDown = parachutersDown + 1; p.setTouched(false); } } } catch (Exception e) { e.printStackTrace(); } } public void initiateDrawParachuters() { drawParachutersGroup1(); } public void drawParachutersGroup1() { // TODO Auto-generated method stub //Parachuter group nr. 1 //Parachuter nr. 2 x = 75; y = 77; Parachuter p1 = new Parachuter(x, y); parachuters.add(p1); //Parachuter nr.1 x = 14; y = 28; Parachuter p = new Parachuter(x, y); parachuters.add(p); //Parachuter nr. 3 x = 250; y = 94; Parachuter p3 = new Parachuter(x, y); parachuters.add(p3); //Parachuter nr. 3 x = 275; y = 80; Parachuter p2 = new Parachuter(x, y); parachuters.add(p2); //Parachuter nr. 5 x = 280; y = 163; Parachuter p5 = new Parachuter(x, y); parachuters.add(p5); x = 125; y = 118; Parachuter p4 = new Parachuter(x, y); parachuters.add(p4); //Parachuter nr. 7 x = 126; y = 247; Parachuter p7 = new Parachuter(x, y); parachuters.add(p7); //Parachuter nr. 6 x = 123; y = 77; Parachuter p6 = new Parachuter(x, y); parachuters.add(p6); } public void drawParachutersGroup2() { // TODO Auto-generated method stub //Parachuter group nr. 2 //Parachuter nr. 5 x = 153; y = 166; Parachuter p5 = new Parachuter(x, y); parachuters.add(p5); x = 133; y = 123; Parachuter p4 = new Parachuter(x, y); parachuters.add(p4); //Parachuter nr. 7 x = 170; y = 213; Parachuter p7 = new Parachuter(x, y); parachuters.add(p7); //Parachuter nr. 6 x = 190; y = 121; Parachuter p6 = new Parachuter(x, y); parachuters.add(p6); } public void drawParachutersGroup3() { // TODO Auto-generated method stub //Parachuter group nr. 3 //Parachuter nr. 2 x = 267; y = 115; Parachuter p1 = new Parachuter(x, y); parachuters.add(p1); //Parachuter nr.1 x = 255; y = 183; Parachuter p = new Parachuter(x, y); parachuters.add(p); //Parachuter nr. 3 x = 170; y = 280; Parachuter p3 = new Parachuter(x, y); parachuters.add(p3); //Parachuter nr. 3 x = 116; y = 80; Parachuter p2 = new Parachuter(x, y); parachuters.add(p2); //Parachuter nr. 5 x = 67; y = 112; Parachuter p5 = new Parachuter(x, y); parachuters.add(p5); x = 260; y = 89; Parachuter p4 = new Parachuter(x, y); parachuters.add(p4); //Parachuter nr. 7 x = 260; y = 113; Parachuter p7 = new Parachuter(x, y); parachuters.add(p7); //Parachuter nr. 6 x = 178; y = 25; Parachuter p6 = new Parachuter(x, y); parachuters.add(p6); } public void drawParachutersGroup4() { // TODO Auto-generated method stub //Parachuter group nr. 1 //Parachuter nr. 2 x = 75; y = 166; Parachuter p1 = new Parachuter(x, y); parachuters.add(p1); //Parachuter nr.1 x = 118; y = 94; Parachuter p = new Parachuter(x, y); parachuters.add(p); //Parachuter nr. 3 x = 38; y = 55; Parachuter p3 = new Parachuter(x, y); parachuters.add(p3); //Parachuter nr. 3 x = 57; y = 18; Parachuter p2 = new Parachuter(x, y); parachuters.add(p2); //Parachuter nr. 5 x = 67; y = 119; Parachuter p5 = new Parachuter(x, y); parachuters.add(p5); x = 217; y = 113; Parachuter p4 = new Parachuter(x, y); parachuters.add(p4); //Parachuter nr. 7 x = 245; y = 234; Parachuter p7 = new Parachuter(x, y); parachuters.add(p7); //Parachuter nr. 6 x = 239; y = 44; Parachuter p6 = new Parachuter(x, y); parachuters.add(p6); } public void drawParachutersGroup5() { // TODO Auto-generated method stub //Parachuter group nr. 1 //Parachuter nr. 2 x = 59; y = 120; Parachuter p1 = new Parachuter(x, y); parachuters.add(p1); //Parachuter nr.1 x = 210; y = 169; Parachuter p = new Parachuter(x, y); parachuters.add(p); //Parachuter nr. 3 x = 199; y = 138; Parachuter p3 = new Parachuter(x, y); parachuters.add(p3); //Parachuter nr. 3 x = 22; y = 307; Parachuter p2 = new Parachuter(x, y); parachuters.add(p2); //Parachuter nr. 5 x = 195; y = 22; Parachuter p5 = new Parachuter(x, y); parachuters.add(p5); x = 157; y = 132; Parachuter p4 = new Parachuter(x, y); parachuters.add(p4); //Parachuter nr. 7 x = 150; y = 183; Parachuter p7 = new Parachuter(x, y); parachuters.add(p7); //Parachuter nr. 6 x = 130; y = 20; Parachuter p6 = new Parachuter(x, y); parachuters.add(p6); } public void drawParachutersGroup6() { // TODO Auto-generated method stub //Parachuter group nr. 1 //Parachuter nr. 2 x = 10; y = 10; Parachuter p1 = new Parachuter(x, y); parachuters.add(p1); //Parachuter nr.1 x = 20; y = 20; Parachuter p = new Parachuter(x, y); parachuters.add(p); //Parachuter nr. 3 x = 30; y = 30; Parachuter p3 = new Parachuter(x, y); parachuters.add(p3); //Parachuter nr. 3 x = 60; y = 60; Parachuter p2 = new Parachuter(x, y); parachuters.add(p2); //Parachuter nr. 5 x = 90; y = 90; Parachuter p5 = new Parachuter(x, y); parachuters.add(p5); x = 120; y = 120; Parachuter p4 = new Parachuter(x, y); parachuters.add(p4); //Parachuter nr. 7 x = 150; y = 150; Parachuter p7 = new Parachuter(x, y); parachuters.add(p7); //Parachuter nr. 6 x = 180; y = 180; Parachuter p6 = new Parachuter(x, y); parachuters.add(p6); } public void drawParachuters() { Parachuter p = new Parachuter(x, y); parachuters.add(p); Toast.makeText(getContext(), "x=" + x + " y=" + y, 15).show(); } public void setRunning(boolean bRun) { running = bRun; } public boolean getRunning() { return running; } } /** Handle to the application context, used to e.g. fetch Drawables. */ private Context mContext; /** Pointer to the text view to display "Paused.." etc. */ private TextView mStatusText; /** The thread that actually draws the animation */ private ExampleThread eThread; public ExampleView(Context context) { super(context); // register our interest in hearing about changes to our surface SurfaceHolder holder = getHolder(); holder.addCallback(this); // create thread only; it's started in surfaceCreated() eThread = new ExampleThread(holder, context, new Handler() { @Override public void handleMessage(Message m) { // mStatusText.setVisibility(m.getData().getInt("viz")); // mStatusText.setText(m.getData().getString("text")); } }); setFocusable(true); } @Override public boolean onTouchEvent(MotionEvent event) { return eThread.onTouchEvent(event); } public ExampleThread getThread() { return eThread; } @Override public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub } public void surfaceCreated(SurfaceHolder holder) { if (eThread.getState() == Thread.State.TERMINATED) { eThread = new ExampleThread(getHolder(), getContext(), getHandler()); eThread.start(); } else { eThread.start(); } } @Override public void surfaceDestroyed(SurfaceHolder holder) { boolean retry = true; eThread.setRunning(false); while (retry) { try { eThread.join(); retry = false; } catch (InterruptedException e) { } } } }

    Read the article

  • How to set Minimum and Maximum Character limitation to EditText in Android?

    - by nishitpatel
    I am new to android here i have very silly problem i want to set my Edit text box minimum and maximum input value. Here I am creating one Simple validation for Edit text it only take A-Z and 0-9 value with minimum 5 and Maximum 8 character. I set the Maximum and other validation as follow. <EditText android:id="@+id/edittextKode_Listing" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginRight="5dp" android:layout_marginLeft="5dp" android:layout_alignTop="@+id/textKode_listing" android:layout_toRightOf="@+id/textKode_listing" android:maxLength="8" android:inputType="textCapCharacters" android:digits="0,1,2,3,4,5,6,7,8,9,ABCDEFGHIJKLMNOPQRSTVUWXYZ" /> but not able to set Minimum requirement. My Edit text is in alert dialog and i also apply the following code to solve this problem ` private void openInboxDialog() { LayoutInflater inflater = this.getLayoutInflater(); // declare dialog view final View dialogView = inflater.inflate(R.layout.kirim_layout, null); final EditText edittextKode = (EditText) dialogView.findViewById(R.id.edittextKode_Listing); final EditText edittextalamat = (EditText) dialogView.findViewById(R.id.edittextAlamat); edittextKode.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { // TODO Auto-generated method stub if(edittextKode.getText().toString().length() > 0){ if(edittextKode.getText().toString().length() < 5) { edittextKode.setError("Error"); Toast.makeText(GPSActivity.this, "Kode listing value not be less than 5", Toast.LENGTH_SHORT).show(); edittextKode.requestFocus(); } } } }); final AlertDialog.Builder builder = new AlertDialog.Builder(GPSActivity.this); builder.setTitle("Kirim").setView(dialogView) .setNeutralButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub gpsCoordinates = (TextView) findViewById(R.id.text_GPS_Coordinates); kode = edittextKode.getText().toString(); alamat = edittextalamat.getText().toString(); catatan = edittextcatatan.getText().toString(); pengirim = edittextPengirim.getText().toString(); if (kode.length() > 0 && alamat.length() > 0 && catatan.length() > 0 && pengirim.length() > 0) { message = "Kode listing : " + kode + "\nAlamat : " + alamat + " \nCatatan : " + catatan + " \n Pengirim : " + pengirim + "\nKoordinat GPS : " + gpsCoordinates.getText().toString(); sendByGmail(); } else { Toast.makeText( getApplicationContext(), "Please fill all three fields to send mail", Toast.LENGTH_LONG).show(); } } }); builder.create(); builder.show(); }` in this alert dialog i have two edittext i want to apply my validation on first edittext i called the setOnFocusChangeListener to check its minimum length on focus change and if length is less than 5 request for focus but it still type in second edittext. please help me out.

    Read the article

  • disable the Home Button and Back Button"

    - by michael
    i want way to disable the Home Button & Back Button when click on checkbox in application , my application on version 4.2.2 i have code but not work when click on checkbox work stop to application public void HardButtonOnClick(View v) { boolean checked1 = ((CheckBox) v).isChecked(); if(checked1) { SQLiteDatabase db; db = openOrCreateDatabase("Saftey.db", SQLiteDatabase.CREATE_IF_NECESSARY, null); db.setVersion(1); db.setLocale(Locale.getDefault()); db.setLockingEnabled(true); ContentValues values = new ContentValues(); values.put("hardBtn", "YES"); db.update("Setting", values, "id = ?", new String[] { "1" }); Toast.makeText(this, "Hard Button Locked", Toast.LENGTH_LONG).show(); //SharedPreferences pref = getSharedPreferences("pref",0); //SharedPreferences.Editor edit = pref.edit(); //edit.putString("hard","yes"); //edit.commit(); /* String Lock="yes" ; Bundle bundle = new Bundle(); bundle.putString("key", Lock); Intent a = new Intent(Change_setting.this, ChildMode.class); a.putExtras(bundle); startActivity(a);*/ super.onAttachedToWindow(); this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD); isLock = true; } else { SQLiteDatabase db; db = openOrCreateDatabase("Saftey.db", SQLiteDatabase.CREATE_IF_NECESSARY, null); db.setVersion(1); db.setLocale(Locale.getDefault()); db.setLockingEnabled(true); ContentValues values = new ContentValues(); values.put("hardBtn", "NO"); db.update("Setting", values, "id = ?", new String[] { "1" }); //SharedPreferences pref = getSharedPreferences("pref",0); //SharedPreferences.Editor edit = pref.edit(); //edit.putString("hard","no"); //edit.commit(); Toast.makeText(this, "Hard Button Un-Locked", Toast.LENGTH_LONG).show(); isLock = false; } } how can work it??

    Read the article

  • checkbox unchecked when i scroll listview in android

    - by Mathew
    I am new to android development. I created a listview with textbox and checkbox. When I check the checkbox and scroll it down to check some other items in the list view, the older ones are unchecked. How to avoid this problem in listview? Please guide me with my code. Here is the code: main.xml: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:id="@+id/TextView01" android:layout_height="wrap_content" android:text="List of items" android:textStyle="normal|bold" android:gravity="center_vertical|center_horizontal" android:layout_width="fill_parent"></TextView> <ListView android:id="@+id/ListView01" android:layout_height="250px" android:layout_width="fill_parent"> </ListView> <Button android:text="Save" android:id="@+id/btnSave" android:layout_width="wrap_content" android:layout_height="wrap_content"> </Button> </LinearLayout> This is the xml page I used to create dynamic list row: listview.xml: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content" android:gravity="left|center" android:layout_width="wrap_content" android:paddingBottom="5px" android:paddingTop="5px" android:paddingLeft="5px"> <TextView android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:textColor="#FFFF00" android:text="hi"></TextView> <TextView android:text="hello" android:id="@+id/TextView02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10px" android:textColor="#0099CC"></TextView> <EditText android:id="@+id/txtbox" android:layout_width="120px" android:layout_height="wrap_content" android:textSize="12sp" android:layout_x="211px" android:layout_y="13px"> </EditText> <CheckBox android:id="@+id/chkbox1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> This is my activity class. CustomListViewActivity.java: package com.listivew; import android.app.Activity; import android.os.Bundle; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class CustomListViewActivity extends Activity { ListView lstView; static Context mContext; Button btnSave; private static class EfficientAdapter extends BaseAdapter { private LayoutInflater mInflater; public EfficientAdapter(Context context) { mInflater = LayoutInflater.from(context); } public int getCount() { return country.length; } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { final ViewHolder holder; if (convertView == null) { convertView = mInflater.inflate(R.layout.listview, parent, false); holder = new ViewHolder(); holder.text = (TextView) convertView .findViewById(R.id.TextView01); holder.text2 = (TextView) convertView .findViewById(R.id.TextView02); holder.txt = (EditText) convertView.findViewById(R.id.txtbox); holder.cbox = (CheckBox) convertView.findViewById(R.id.chkbox1); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.text.setText(curr[position]); holder.text2.setText(country[position]); holder.txt.setText(""); holder.cbox.setChecked(false); return convertView; } public class ViewHolder { TextView text; TextView text2; EditText txt; CheckBox cbox; } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); lstView = (ListView) findViewById(R.id.ListView01); lstView.setAdapter(new EfficientAdapter(this)); btnSave = (Button)findViewById(R.id.btnSave); mContext = this; btnSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // I want to print the text which is in the listview one by one. //Later i will insert it in the database // Toast.makeText(getBaseContext(), "EditText Value, checkbox value and other values", Toast.LENGTH_SHORT).show(); for (int i = 0; i < lstView.getCount(); i++) { View listOrderView; listOrderView = lstView.getChildAt(i); try{ EditText txtAmt = (EditText)listOrderView.findViewById(R.id.txtbox); CheckBox cbValue = (CheckBox)listOrderView.findViewById(R.id.chkbox1); if(cbValue.isChecked()== true){ String amt = txtAmt.getText().toString(); Toast.makeText(getBaseContext(), "Amount is :"+amt, Toast.LENGTH_SHORT).show(); } }catch (Exception e) { // TODO: handle exception } } } }); } private static final String[] country = { "item1", "item2", "item3", "item4", "item5", "item6","item7", "item8", "item9", "item10", "item11", "item12" }; private static final String[] curr = { "1", "2", "3", "4", "5", "6","7", "8", "9", "10", "11", "12" }; } Please help me to slove this problem. I have referred in many places. But I could not get proper answer to solve this problem. Please provide me the code to avoid unchecking the checkbox while scrolling up and down. Thank you.

    Read the article

  • Android : changing Locale within the app itself

    - by Hubert
    My users can change the Locale within the app (they may want to keep their phone settings in English but read the content of my app in French, Dutch or any other language ...) Why is this working perfectly fine in 1.5/1.6 but NOT in 2.0 anymore ??? @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()){ case 201: Locale locale2 = new Locale("fr"); Locale.setDefault(locale2); Configuration config2 = new Configuration(); config2.locale = locale2; getBaseContext().getResources().updateConfiguration(config2, getBaseContext().getResources().getDisplayMetrics()); // loading data ... refresh(); // refresh the tabs and their content refresh_Tab (); break; case 201: etc... The problem is that the MENU "shrinks" more and more everytime the user is going through the lines of code above ... This is the Menu that gets shrunk: @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, 100, 1, "REFRESH").setIcon(android.R.drawable.ic_menu_compass); SubMenu langMenu = menu.addSubMenu(0, 200, 2, "NL-FR").setIcon(android.R.drawable.ic_menu_rotate); langMenu.add(1, 201, 0, "Nederlands"); langMenu.add(1, 202, 0, "Français"); menu.add(0, 250, 4, R.string.OptionMenu2).setIcon(android.R.drawable.ic_menu_send); menu.add(0, 300, 5, R.string.OptionMenu3).setIcon(android.R.drawable.ic_menu_preferences); menu.add(0, 350, 3, R.string.OptionMenu4).setIcon(android.R.drawable.ic_menu_more); menu.add(0, 400, 6, "Exit").setIcon(android.R.drawable.ic_menu_delete); return super.onCreateOptionsMenu(menu); } What should I do in API Level 5 to make this work again ? HERE IS THE FULL CODE IF YOU WANT TO TEST THIS : import java.util.Locale; import android.app.Activity; import android.content.res.Configuration; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.widget.Toast; public class Main extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override public boolean onCreateOptionsMenu(Menu menu) { SubMenu langMenu = menu.addSubMenu(0, 200, 2, "NL-FR").setIcon(android.R.drawable.ic_menu_rotate); langMenu.add(1, 201, 0, "Nederlands"); langMenu.add(1, 202, 0, "Français"); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()){ case 201: Locale locale = new Locale("nl"); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); Toast.makeText(this, "Locale in Nederlands !", Toast.LENGTH_LONG).show(); break; case 202: Locale locale2 = new Locale("fr"); Locale.setDefault(locale2); Configuration config2 = new Configuration(); config2.locale = locale2; getBaseContext().getResources().updateConfiguration(config2, getBaseContext().getResources().getDisplayMetrics()); Toast.makeText(this, "Locale en Français !", Toast.LENGTH_LONG).show(); break; } return super.onOptionsItemSelected(item); } } AND HERE IS THE MANIFEST : <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.cousinHub.ChangeLocale" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".Main" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-sdk android:minSdkVersion="3" /> </manifest> THIS IS WHAT I FOUND : <uses-sdk android:minSdkVersion="5" /> = IT WORKS JUST FINE ... <uses-sdk android:minSdkVersion="3" /> = Menu shrinks every time you change the locale !!! as I want to keep my application accessible for users on 1.5, what should I do ??

    Read the article

  • Saving to SharedPreferences from custom DialogPreference

    - by Ronnie
    I've currently got a preferences screen, and I've created a custom class that extends DialogPreference and is called from within my Preferences. My preferences data seems store/retrieve from SharedPreferences without an issue, but I'm trying to add 2 more sets of settings from the DialogPreference. Basically I have two issues that I have not been able to find. Every site I've seen gives me the same standard info to save/restore data and I'm still having problems. Firstly I'm trying to save a username and password to my SharedPreferences (visible in the last block of code) and if possibly I'd like to be able to do it in the onClick(). My preferences XML that calls my DialogPreference: <?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <PreferenceCategory> <com.rone.optusmon.AccDialog android:key="AccSettings" android:title="Account Settings" android:negativeButtonText="Cancel" android:positiveButtonText="Save" /> </PreferenceCategory> </PreferenceScreen> My Preference Activity Class: package com.rone.optusmon; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.preference.Preference; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceActivity; import android.view.KeyEvent; public class EditPreferences extends PreferenceActivity { Context context = this; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); } } My Custom DialogPreference Class file: package com.rone.optusmon; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.preference.DialogPreference; import android.preference.PreferenceManager; import android.text.method.PasswordTransformationMethod; import android.util.AttributeSet; import android.view.View; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class AccDialog extends DialogPreference implements DialogInterface.OnClickListener { private TextView mUsername, mPassword; private EditText mUserbox, mPassbox; CharSequence mPassboxdata, mUserboxdata; private CheckBox mShowchar; private Context mContext; private int mWhichButtonClicked; public AccDialog(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; } @Override protected View onCreateDialogView() { @SuppressWarnings("unused") LinearLayout.LayoutParams params; LinearLayout layout = new LinearLayout(mContext); layout.setOrientation(LinearLayout.VERTICAL); layout.setPadding(10, 10, 10, 10); layout.setBackgroundColor(0xFF000000); mUsername = new TextView(mContext); mUsername.setText("Username:"); mUsername.setTextColor(0xFFFFFFFF); mUsername.setPadding(0, 8, 0, 3); mUserbox = new EditText(mContext); mUserbox.setSingleLine(true); mUserbox.setSelectAllOnFocus(true); mPassword = new TextView(mContext); mPassword.setText("Password:"); mPassword.setTextColor(0xFFFFFFFF); mPassbox = new EditText(mContext); mPassbox.setSingleLine(true); mPassbox.setSelectAllOnFocus(true); mShowchar = new CheckBox(mContext); mShowchar.setOnCheckedChangeListener(mShowchar_listener); mShowchar.setText("Show Characters"); mShowchar.setTextColor(0xFFFFFFFF); mShowchar.setChecked(false); if(!mShowchar.isChecked()) { mPassbox.setTransformationMethod(new PasswordTransformationMethod()); } layout.addView(mUsername); layout.addView(mUserbox); layout.addView(mPassword); layout.addView(mPassbox); layout.addView(mShowchar); return layout; // Access default SharedPreferences SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); } public void onClick(DialogInterface dialog, int which) { mWhichButtonClicked = which; // if statement to set save/cancel button roles if (mWhichButtonClicked == -1) { Toast.makeText(mContext, "Save was clicked", Toast.LENGTH_SHORT).show(); mUserboxdata = mUserbox.getText(); mPassboxdata = mPassbox.getText(); // Save user preferences SharedPreferences settings = getDefaultSharedPreferences(this); SharedPreferences.Editor editor = settings.edit(); editor.putString("usernamekey", (String) mUserboxdata); editor.putString("passwordkey", (String) mPassboxdata); } else { Toast.makeText(mContext, "Cancel was clicked", Toast.LENGTH_SHORT).show(); } } } In my SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); line, Eclipse says "The method getDefaultSharedPreferences(AccDialog) is undefined for the type AccDialog". I've attempted to change the context to my preferences class, use a blank context and I've also tried naming my SharedPrefs and using "getSharedPreferences()" as well. I'm just not sure exactly what I'm doing here. As I'm quite new to Java/Android/coding in general, could you please be as detailed as possible with any help, eg. which of my files I need to write the code in and whereabouts in that file should I write it (i.e. onCreate(), onClick(), etc) Edit: I will need to the preferences to be Application-wide accessible, not activity-wide. Thanks

    Read the article

  • Error showing is NullPointerException [duplicate]

    - by user3659612
    This question already has an answer here: How to check a string against null in java? 11 answers I was trying to code a wifi scanner which does 20 scans but it shows NullPointerException at if(bssid[j].equals(null)){ My code is slightly huge package com.example.scanner; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import android.annotation.SuppressLint; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.wifi.ScanResult; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Bundle; import android.os.Environment; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; public class MainActivity extends ActionBarActivity { WifiManager wifi; WifiScanReceiver wifireciever; WifiInfo info; Button scan, save; List<ScanResult> wifilist; ListView list; String wifis[]; String name; String[] ssid = new String[100]; String[] bssid = new String[100]; int[] lvl = new int[100]; int[] count = new int[100]; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_main); list=(ListView)findViewById(R.id.listView1); scan=(Button)findViewById(R.id.button1); save=(Button)findViewById(R.id.button2); scan.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub wifi=(WifiManager)getSystemService(Context.WIFI_SERVICE); if (wifi.isWifiEnabled()==false){ wifi.setWifiEnabled(true); } wifireciever = new WifiScanReceiver(); for (int i=0;i<20;i++){ registerReceiver(wifireciever, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)); wifi.startScan(); if (i==19){ Toast.makeText(getBaseContext(), "Scan Finish", Toast.LENGTH_LONG).show(); } } } }); save.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub savedata(); } }); } protected void savedata() { // TODO Auto-generated method stub try { File sdcard = Environment.getExternalStorageDirectory(); File directory = new File(sdcard.getAbsolutePath() + "/WIFI_RESULT"); directory.mkdirs(); name = new SimpleDateFormat("yyyy-MM-dd HH mm ss").format(new Date()); File file = new File(directory,name + "wifi_data.txt"); FileOutputStream fou = new FileOutputStream(file); OutputStreamWriter osw = new OutputStreamWriter(fou); try { for (int i =0; i < list.getCount(); i++){ osw.append(list.getItemAtPosition(i).toString()); } osw.flush(); osw.close(); Toast.makeText(getBaseContext(), "Saved", Toast.LENGTH_LONG).show(); } catch (IOException e){ e.printStackTrace(); } } catch (FileNotFoundException e){ e.printStackTrace(); } } class WifiScanReceiver extends BroadcastReceiver { @SuppressLint("UseValueOf") public void onReceive(Context c, Intent intent) { int a =0; wifi.startScan(); List<ScanResult> wifilist = wifi.getScanResults(); if (a<wifilist.size()){ a=wifilist.size(); } for(int j=0;j<wifilist.size();j++){ if(bssid[j].equals(null)){ ssid[j] = wifilist.get(j).SSID.toString(); bssid[j] = wifilist.get(j).BSSID.toString(); lvl[j] = wifilist.get(j).level; count[j]++; } else if (bssid[j].equals(wifilist.get(j).BSSID.toString())){ lvl[j] = lvl[j] + wifilist.get(j).level; count[j]++; } } wifis = new String[a]; for (int i =0; i<a; i++){ wifis[i] = ("\n" + ssid[i] + "\n AP Address" + bssid[i] + "\n Signal Strength:" + lvl[i]/count[i]).toString(); } list.setAdapter(new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,wifis)); } } protected void onDestroy() { unregisterReceiver(wifireciever); super.onPause(); } protected void onResume() { registerReceiver(wifireciever, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)); super.onResume(); } @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; } } NullPointerException at that point mean my array bssid isn't initialize. So I just want to know how to initialize it in main activity so that I can use that string bssid anywhere.

    Read the article

  • zxing project on android

    - by Aisthesis Cronos
    Hello everybody Many weeks ago,I tried to work on a mini project on Android OS requires ZXING, I followed several tutorials on this web site and on other Example: tuto1, and many tags and tutorials here tuto2, tuto3 ... But I failed each time. I can't import the android project into eclipse IDE to compile it with my code "not via Intent zxing APK-and my program like this example : private Button.OnClickListener btScanListener = new Button.OnClickListener() { public void onClick(View v) { Intent intent = new Intent("com.google.zxing.client.android.SCAN"); intent.putExtra("SCAN_MODE", "QR_CODE_MODE"); try { startActivityForResult(intent, REQUEST_SCAN); } catch (ActivityNotFoundException e) { Toast.makeText(Main.this, "Barcode Scanner not intaled ", 2000).show(); } } }; public void onActivityResult(int reqCode, int resCode, Intent intent) { if (REQUEST_SCAN == reqCode) { if (RESULT_OK == resCode) { String contents = intent.getStringExtra("SCAN_RESULT"); Toast.makeText(this, "Succès : " + contents, 2000).show(); } else if (RESULT_CANCELED == resCode) { Toast.makeText(this, "Scan annulé", 2000).show(); } } }` ". I feel disappointed, frustrated and sad. I still have errors after importing the project. I tried both versions 1.5 and 1.6 zxing I tried to import the project c: \ ZXing-1.6 \ android, and an other new project with c: \ ZXing-1.6 \ zxing-1.6 \ android,I cheked out SVN: ttp: / / zxing.googlecode.com / svn / trunk / zxing-read-only with tortoiseSVN and reproduce the same work, but unfortunately without results! I really fed up with myself ... Please help me to solve this problem.how can I import the project and compile it correctly in my own project? 1 - I use Windows 7 64-bit Home Premium 2 - Eclipse IDE for Java EE Web Developers. Version: Helios Service Release 2 Build id: 20110218-0911 What is the effective and sure method to run this, otherwise if there is a video or a guide details or someone who already done it previously I would really appreciate it if someone would help me out

    Read the article

  • Playing video from URL -Android

    - by Rajeev
    In the following code what ami doing wrong the video dosnt seem to play here.Is that the permission issue if so what should be included in the manifest file this main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" android:baselineAligned="true"> <LinearLayout android:layout_height="match_parent" android:layout_width="wrap_content" android:id="@+id/linearLayout2"></LinearLayout> <MediaController android:id="@+id/mediacnt" android:layout_width="wrap_content" android:layout_height="wrap_content"></MediaController> <LinearLayout android:layout_height="match_parent" android:layout_width="wrap_content" android:id="@+id/linearLayout1" android:orientation="vertical"></LinearLayout> <Gallery android:layout_height="wrap_content" android:id="@+id/gallery" android:layout_width="wrap_content" android:layout_weight="1"></Gallery> <VideoView android:layout_height="match_parent" android:id="@+id/vv" android:layout_width="wrap_content"></VideoView> </LinearLayout> this is java class package com.gallery; import java.net.URL; import android.app.Activity; import android.app.Activity; import android.net.Uri; import android.os.Bundle; import android.widget.MediaController; import android.widget.Toast; import android.widget.VideoView; public class GalleryActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Toast.makeText(GalleryActivity.this, "Hello world", Toast.LENGTH_LONG).show(); VideoView videoView = (VideoView) findViewById(R.id.vv); MediaController mediaController = new MediaController(this); mediaController.setAnchorView(videoView); // Set video link (mp4 format ) Uri video = Uri.parse("http://www.youtube.com/watch?v=lEbxLDuecHU&playnext=1&list=PL040F3034C69B1674"); videoView.setMediaController(mediaController); videoView.setVideoURI(video); videoView.start(); } }

    Read the article

  • Android GPS cloud of confusion!

    - by Anthony Forloney
    I am trying to design my first Android application with the use of GPS. As of right now, I have a drawable button that when clicked, alerts a Toast message of the longitude and latitude. I have tried to use the telnet localhost 5554 and then geo fix #number #number to feed in values but no results display just 0 0. I have also tried DDMS way of sending GPS coordinates and I get the same thing. My question is what exactly is the code equivalent to the geo fix and the DDMS way of sending coordinates. I have used Location, LocationManger and LocationListener but I am not sure which is the right choice. Could anyone explain to me what the code-equivalent just so I can get a better understanding of how to fix my application not working. Code is given, just in case if the error exists with the code @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button button = (Button) findViewById(R.id.track); button.setOnClickListener(this); LocationManager location =(LocationManager)getSystemService(Context.LOCATION_SERVICE); Location loc = location.getLastKnownLocation(location.GPS_PROVIDER); updateWithNewLocation(loc); } private final LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { updateWithNewLocation(location); } private void updateWithNewLocation(Location l) { longitude = l.getLongitude(); latitude = l.getLatitude(); provider = l.getProvider(); } public void onClick(View v) { Toast.makeText(this, "Your location is " + longitude + " and " + latitude + " provided by: " + provider, Toast.LENGTH_SHORT).show(); } }

    Read the article

  • Error Message-The source attachment does not contain the source for the file ListView.class

    - by user603695
    Hello, new to Android. I get the following message in the debugger perspective: The source attachment does not contain the source for the file ListView.class You can change the source attachment by clicking the change attached Source Below Needless to say the app errors. I've tried to change the source attachment to the location path: C:/Program Files/Android/android-sdk-windows/platforms/android-8/android.jar However, this did not work. Any thoughts would be much appreciated. Code is: import android.app.ListActivity; import android.os.Bundle; import android.view.*; import android.widget.*; public class HelloListView extends ListActivity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setListAdapter(new ArrayAdapter<String>(this, R.layout.main, COUNTRIES)); ListView lv = getListView(); lv.setTextFilterEnabled(true); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // When clicked, show a toast with the TextView text Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show(); } }); } static final String[] COUNTRIES = new String[] { "Afghanistan", "Albania", "Algeria", "American Samoa... Thanks!

    Read the article

  • Null Pointer Exception in my BroadcastReceiver class

    - by user1760007
    I want to search a db and toast a specific column on the startup of the phone. The app keeps crashing and getting an exception even though I feel as the code is correct. @Override public void onReceive(Context ctx, Intent intent) { Log.d("omg", "1"); DBAdapter do = new DBAdapter(ctx); Log.d("omg", "2"); Cursor cursor = do.fetchAllItems(); Log.d("omg", "3"); if (cursor.moveToFirst()) { Log.d("omg", "4"); do { Log.d("omg", "5"); String title = cursor.getString(cursor.getColumnIndex("item")); Log.d("omg", "6"); // i = cursor.getInt(cursor.getColumnIndex("id")); Toast.makeText(ctx, title, Toast.LENGTH_LONG).show(); } while (cursor.moveToNext()); } cursor.close(); } The frustrating part is that I don't see any of my "omg" logs show up in logcat. I only see when my application crashes. I get three lines of errors in logcat. 10-19 12:31:11.656: E/AndroidRuntime(1471): java.lang.RuntimeException: Unable to start receiver com.test.toaster.MyReciever: java.lang.NullPointerException 10-19 12:31:11.656: E/AndroidRuntime(1471): at com.test.toaster.DBAdapter.fetchAllItems(DBAdapter.java:96) 10-19 12:31:11.656: E/AndroidRuntime(1471): at com.test.toaster.MyReciever.onReceive(MyReciever.java:26) For anyone interested, here is my DBAdapter fetchAllItems code: public Cursor fetchAllItems() { return mDb.query(DATABASE_TABLE, new String[] { KEY_ITEM, KEY_PRIORITY, KEY_ROWID }, null, null, null, null, null); }

    Read the article

  • Android ACTION_BOOT_COMPLETED called everytime?

    - by user3976029
    I am trying to write a code in Android , to create a condition during booting but my condition satisfies everytime ( during booting as well as during running of the device also). I am trying to do is , to execute the condition during the booting only. My Code : MainActivity.java package com.example.bootingtest; import android.os.Bundle; import android.widget.Toast; import android.app.Activity; import android.content.Intent; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (Intent.ACTION_BOOT_COMPLETED!=null) { Toast.makeText(getApplicationContext(), "Device is booting ...", Toast.LENGTH_LONG).show(); } } } I have given manifest permission . <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> I want to execute this condition only during booting or device start-up but this condition satisfies every time , whenever i open the app. Please suggest me , how can i run the condition only during the device booting or start-up. Please help me out.

    Read the article

  • Android JSON HttpClient to send data to PHP server with HttpResponse

    - by Scoobler
    I am currently trying to send some data from and Android application to a php server (both are controlled by me). There is alot of data collected on a form in the app, this is written to the database. This all works. In my main code, firstly I create a JSONObject (I have cut it down here for this example): JSONObject j = new JSONObject(); j.put("engineer", "me"); j.put("date", "today"); j.put("fuel", "full"); j.put("car", "mine"); j.put("distance", "miles"); Next I pass the object over for sending, and receive the response: String url = "http://www.server.com/thisfile.php"; HttpResponse re = HTTPPoster.doPost(url, j); String temp = EntityUtils.toString(re.getEntity()); if (temp.compareTo("SUCCESS")==0) { Toast.makeText(this, "Sending complete!", Toast.LENGTH_LONG).show(); } The HTTPPoster class: public static HttpResponse doPost(String url, JSONObject c) throws ClientProtocolException, IOException { HttpClient httpclient = new DefaultHttpClient(); HttpPost request = new HttpPost(url); HttpEntity entity; StringEntity s = new StringEntity(c.toString()); s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); entity = s; request.setEntity(entity); HttpResponse response; response = httpclient.execute(request); return response; } This gets a response, but the server is returning a 403 - Forbidden response. I have tried changing the doPost function a little (this is actually a little better, as I said I have alot to send, basically 3 of the same form with different data - so I create 3 JSONObjects, one for each form entry - the entries come from the DB instead of the static example I am using). Firstly I changed the call over a bit: String url = "http://www.orsas.com/ServiceMatalan.php"; Map<String, String> kvPairs = new HashMap<String, String>(); kvPairs.put("vehicle", j.toString()); // Normally I would pass two more JSONObjects..... HttpResponse re = HTTPPoster.doPost(url, kvPairs); String temp = EntityUtils.toString(re.getEntity()); if (temp.compareTo("SUCCESS")==0) { Toast.makeText(this, "Sending complete!", Toast.LENGTH_LONG).show(); } Ok so the changes to the doPost function: public static HttpResponse doPost(String url, Map<String, String> kvPairs) throws ClientProtocolException, IOException { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); if (kvPairs != null && kvPairs.isEmpty() == false) { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(kvPairs.size()); String k, v; Iterator<String> itKeys = kvPairs.keySet().iterator(); while (itKeys.hasNext()) { k = itKeys.next(); v = kvPairs.get(k); nameValuePairs.add(new BasicNameValuePair(k, v)); } httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); } HttpResponse response; response = httpclient.execute(httppost); return response; } Ok So this returns a response 200 int statusCode = re.getStatusLine().getStatusCode(); However the data received on the server cannot be parsed to a JSON string. It is badly formatted I think (this is the first time I have used JSON): If in the php file I do an echo on $_POST['vehicle'] I get the following: {\"date\":\"today\",\"engineer\":\"me\"} Can anyone tell me where I am going wrong, or if there is a better way to achieve what I am trying to do? Hopefully the above makes sense!

    Read the article

  • [Android] Launching activity from widget

    - by Steve H
    Hi, I'm trying to do something which really ought to be quite easy, but it's driving me crazy. I'm trying to launch an activity when a home screen widget is pressed, such as a configuration activity for the widget. I think I've followed word for word the tutorial on the Android Developers website, and even a few unofficial tutorials as well, but I must be missing something important as it doesn't work. Here is the code: public class VolumeChangerWidget extends AppWidgetProvider { public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds){ final int N = appWidgetIds.length; for (int i=0; i < N; i++) { int appWidgetId = appWidgetIds[i]; Log.d("Steve", "Running for appWidgetId " + appWidgetId); Toast.makeText(context, "Hello from onUpdate", Toast.LENGTH_SHORT); Log.d("Steve", "After the toast line"); Intent intent = new Intent(context, WidgetTest.class); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget); views.setOnClickPendingIntent(R.id.button, pendingIntent); appWidgetManager.updateAppWidget(appWidgetId, views); } } } When adding the widget to the homescreen, Logcat shows the two debugging lines, though not the Toast. (Any ideas why not?) However, more vexing is that when I then click on the button with the PendingIntent associated with it, nothing happens at all. I know the "WidgetTest" activity can run because if I set up an Intent from within the main activity, it launches fine. In case it matters, here is the Android Manifest file: <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.steve" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".Volume_Change_Program" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".WidgetTest" android:label="@string/hello"> <intent_filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent_filter> </activity> <receiver android:name=".VolumeChangerWidget" > <intent-filter> <action android:name="android.appwidget.action.APPWIDGET_UPDATE" /> </intent-filter> <meta-data android:name="android.appwidget.provider" android:resource="@xml/volume_changer_info" /> </receiver> </application> <uses-sdk android:minSdkVersion="3" /> Is there a way to test where the fault is? I.e. is the fault that the button isn't linked properly to the PendingIntent, or that the PendingIntent or Intent isn't finding WidgetTest.class, etc? Thanks very much for your help! Steve

    Read the article

  • How do I load an image from sd card into coverview

    - by Jolene
    I am doing an application which consists of a cover flow. Currently I am trying to make the cover flow images be obtained from the sd card. But I am not exactly sure how should I display the image. this is the image adapter: public class ImageAdapter extends BaseAdapter { int mGalleryItemBackground; private Context mContext; private FileInputStream fis; private Integer[] mImageIds = { //Instead of using r.drawable, i need to load the images from my sd card instead R.drawable.futsing, R.drawable.futsing2 }; private ImageView[] mImages; public ImageAdapter(Context c) { mContext = c; mImages = new ImageView[mImageIds.length]; } public int getCount() { return mImageIds.length; } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } @TargetApi(8) public View getView(int position, View convertView, ViewGroup parent) { int screenSize = getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK; ImageView i = new ImageView(mContext); i.setImageResource(mImageIds[position]); switch(screenSize) { case Configuration.SCREENLAYOUT_SIZE_XLARGE: //Toast.makeText(this, "Small screen",Toast.LENGTH_LONG).show(); Display display4 = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); int rotation4 = display4.getRotation(); Log.d("XLarge:",String.valueOf(rotation4)); /** LANDSCAPE **/ if(rotation4 == 0 || rotation4 == 2) { i.setLayoutParams(new CoverFlow.LayoutParams(300, 300)); i.setScaleType(ImageView.ScaleType.CENTER_INSIDE); BitmapDrawable drawable = (BitmapDrawable) i.getDrawable(); drawable.setAntiAlias(true); return i; } /** PORTRAIT **/ else if (rotation4 == 1 || rotation4 == 3) { i.setLayoutParams(new CoverFlow.LayoutParams(650, 650)); i.setScaleType(ImageView.ScaleType.CENTER_INSIDE); BitmapDrawable drawable = (BitmapDrawable) i.getDrawable(); drawable.setAntiAlias(true); return i; } break; default: } return null; } /** Returns the size (0.0f to 1.0f) of the views * depending on the 'offset' to the center. */ public float getScale(boolean focused, int offset) { /* Formula: 1 / (2 ^ offset) */ return Math.max(0, 1.0f / (float)Math.pow(2, Math.abs(offset))); } } and this is how i download and save the file. I need to use the image saved and upload it into my coverflow // IF METHOD TO DOWNLOAD IMAGE void downloadFile() { new Thread(new Runnable(){ // RUN IN BACKGROUND THREAD TO AVOID FREEZING OF UI public void run(){ Bitmap bmImg; URL myFileUrl = null; try { //for (int i = 0; i < urlList.size(); i ++) //{ //url = urlList.get(i); myFileUrl = new URL("http://static.adzerk.net/Advertisers/d18eea9d28f3490b8dcbfa9e38f8336e.jpg"); // RETRIEVE IMAGE URL //} } catch (MalformedURLException e) { e.printStackTrace(); } try { HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection(); conn.setDoInput(true); conn.connect(); InputStream in = conn.getInputStream(); Log.i("im connected", "Download"); bmImg = BitmapFactory.decodeStream(in); saveFile(bmImg); } catch (IOException e) { e.printStackTrace(); }} }).start(); // START THREAD } // SAVE THE IMAGE AS JPG FILE private void saveFile(Bitmap bmImg) { File filename; try { // GET EXTERNAL STORAGE, SAVE FILE THERE File storagePath = new File(Environment.getExternalStorageDirectory(),"Covers"); storagePath.mkdirs(); filename = new File(storagePath + "/image.jpg"); FileOutputStream out = new FileOutputStream(filename); bmImg.compress(Bitmap.CompressFormat.JPEG, 90, out); out.flush(); out.close(); MediaStore.Images.Media.insertImage(getContentResolver(),filename.getAbsolutePath(), filename.getName(), filename.getName()); // ONCE THE DOWNLOAD FINISHES, CLOSE DIALOG Toast.makeText(getApplicationContext(), "Image Saved!", Toast.LENGTH_SHORT).show(); } catch (Exception e) { e.printStackTrace(); } }

    Read the article

  • Unable to start ServiceIntent android

    - by Mj1992
    I don't know why my service class is not working although it was working fine before. I've the following service class. public class MyIntentService extends IntentService { private static PowerManager.WakeLock sWakeLock; private static final Object LOCK = MyIntentService.class; public MyIntentService() { super("MuazzamService"); } @Override protected void onHandleIntent(Intent intent) { try { String action = intent.getAction(); <-- breakpoint if (action.equals("com.google.android.c2dm.intent.REGISTRATION")) <-- passes by { handleRegistration(intent); } else if (action.equals("com.google.android.c2dm.intent.RECEIVE")) { handleMessage(intent); } } finally { synchronized(LOCK) { sWakeLock.release(); } } } private void handleRegistration(Intent intent) { try { String registrationId = intent.getStringExtra("registration_id"); String error = intent.getStringExtra("error"); String unregistered = intent.getStringExtra("unregistered"); if (registrationId != null) { this.SendRegistrationIDViaHttp(registrationId); Log.i("Regid",registrationId); } if (unregistered != null) {} if (error != null) { if ("SERVICE_NOT_AVAILABLE".equals(error)) { Log.e("ServiceNoAvail",error); } else { Log.i("Error In Recieveing regid", "Received error: " + error); } } } catch(Exception e) { Log.e("ErrorHai(MIS0)",e.toString()); e.printStackTrace(); } } private void SendRegistrationIDViaHttp(String regID) { HttpClient httpclient = new DefaultHttpClient(); try { HttpGet httpget = new HttpGet("http://10.116.27.107/php/GCM/AndroidRequest.php?registrationID="+regID+"&[email protected]"); //test purposes k liye muazzam HttpResponse response = httpclient.execute(httpget); HttpEntity entity=response.getEntity(); if(entity!=null) { InputStream inputStream=entity.getContent(); String result= convertStreamToString(inputStream); Log.i("finalAnswer",result); // Toast.makeText(getApplicationContext(),regID, Toast.LENGTH_LONG).show(); } } catch (ClientProtocolException e) { Log.e("errorhai",e.getMessage()); e.printStackTrace(); } catch (IOException e) { Log.e("errorhai",e.getMessage()); e.printStackTrace(); } } private static String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { Log.e("ErrorHai(MIS)",e.toString()); e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { Log.e("ErrorHai(MIS2)",e.toString()); e.printStackTrace(); } } return sb.toString(); } private void handleMessage(Intent intent) { try { String score = intent.getStringExtra("score"); String time = intent.getStringExtra("time"); Toast.makeText(getApplicationContext(), "hjhhjjhjhjh", Toast.LENGTH_LONG).show(); Log.e("GetExtraScore",score.toString()); Log.e("GetExtratime",time.toString()); } catch(NullPointerException e) { Log.e("je bat",e.getMessage()); } } static void runIntentInService(Context context,Intent intent){ synchronized(LOCK) { if (sWakeLock == null) { PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); sWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "my_wakelock"); } } sWakeLock.acquire(); intent.setClassName(context, MyIntentService.class.getName()); context.startService(intent); } } and here's how I am calling the service as mentioned in the android docs. Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER"); registrationIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0)); registrationIntent.putExtra("sender",Sender_ID); startService(registrationIntent); I've declared the service in the manifest file inside the application tag. <service android:name="com.pack.gcm.MyIntentService" android:enabled="true"/> I placed a breakpoint in my IntentService class but it never goes there.But if I declare my registrationIntent like this Intent registrationIntent = new Intent(getApplicationContext(),com.pack.gcm.MyIntentService); It works and goes to the breakpoint I've placed but intent.getAction() contains null and hence it doesn't go into the if condition placed after those lines. It says 07-08 02:10:03.755: W/ActivityManager(60): Unable to start service Intent { act=com.google.android.c2dm.intent.REGISTER (has extras) }: not found in the logcat.

    Read the article

  • app not working

    - by pranay
    hi, i have written a simple app which would speak out to the user any incoming message. Both programmes seem to work perfectly when i lauched them as two separate pgms , but on keeping them in the same project/package only the speaker programme screen is seen and the receiver pgm doesn't seem to work . Can someone please help me out on it? the speaker pgm is: package com.example.TextSpeaker; import java.util.Locale; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.speech.tts.TextToSpeech; import android.speech.tts.TextToSpeech.OnInitListener; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; // the following programme converts the msg user to speech public class TextSpeaker extends Activity implements OnInitListener { /** Called when the activity is first created. */ int MY_DATA_CHECK_CODE = 0; public TextToSpeech mtts; public Button button; //public EditText edittext; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); button = (Button)findViewById(R.id.button); //edit text=(EditText)findViewById(R.id.edittext); button.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { //mtts.speak(edittext.getText().toString(), TextToSpeech.QUEUE_FLUSH, null); Toast.makeText(getApplicationContext(), "The service has been started\n Every new message will now be read out", Toast.LENGTH_LONG).show(); } }); Intent myintent = new Intent(); myintent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA); startActivityForResult(myintent, MY_DATA_CHECK_CODE); } protected void onActivityResult(int requestcode,int resultcode,Intent data) { if(requestcode == MY_DATA_CHECK_CODE) { if(resultcode==TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) { // success so create the TTS engine mtts = new TextToSpeech(this,this); mtts.setLanguage(Locale.ENGLISH); } else { //install the Engine Intent install = new Intent(); install.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA); startActivity(install); } } } public void onDestroy(Bundle savedInstanceStatBundle) { mtts.shutdown(); } public void onPause() { super.onPause(); // if our app has no focus if(mtts!=null) mtts.stop(); } @Override public void onInit(int status) { if(status==TextToSpeech.SUCCESS) button.setEnabled(true); } } and the Receiver programme is: package com.example.TextSpeaker; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.speech.tts.TextToSpeech; import android.telephony.SmsMessage; // supports both gsm and cdma import android.widget.Toast; public class Receiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); SmsMessage[] msgs = null; String str=""; if(bundle!=null) { // retrive the sms received Object[] pdus = (Object[])bundle.get("pdus"); msgs = new SmsMessage[pdus.length]; for(int i=0;i } } }

    Read the article

  • SurfaceView drawn on top of other elements after coming back from specific activity

    - by spirytus
    I have an activity with video preview displayed via SurfaceView and other views positioned over it. The problem is when user navigates to Settings activity (code below) and comes back then the surfaceview is drawn on top of everything else. This does not happen when user goes to another activity I have, neither when user navigates outside of app eg. to task manager. Now, you see in code below that I have setContentVIew() call wrapped in conditionals so it is not called every time when onStart() is executed. If its not wrapped in if statements then all works fine, but its causing loosing lots of memory (5MB+) each time onStart() is called. I tried various combinations and nothing seems to work so any help would be much appreciated. @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Toast.makeText(this,"Create ", 2000).show(); // set 32 bit window (draw correctly transparent images) getWindow().getAttributes().format = android.graphics.PixelFormat.RGBA_8888; // set the layout of the screen based on preferences of the user sharedPref = PreferenceManager.getDefaultSharedPreferences(this); } public void onStart() { super.onStart(); String syncConnPref = null; syncConnPref = sharedPref.getString("screensLayouts", "default"); if(syncConnPref.contentEquals("default") && currentlLayout!="default") { setContentView(R.layout.fight_recorder_default); } else if(syncConnPref.contentEquals("simple") && currentlLayout!="simple") { setContentView(R.layout.fight_recorder_simple); } // I I uncomment line below so it will be called every time without conditionals above, it works fine but every time onStart() is called I'm losing 5+ MB memory (memory leak?). The preview however shows under the other elements exactly as I need memory leak makes it unusable after few times though // setContentView(R.layout.fight_recorder_default); if(getCamera()==null) { Toast.makeText(this,"Sorry, camera is not available and fight recording will not be permanently stored",2000).show(); // TODO also in here put some code replacing the background with something nice return; } // now we have camera ready and we need surface to display picture from camera on so // we instantiate CameraPreviw object which is simply surfaceView containing holder object. // holder object is the surface where the image will be drawn onto // this is where camera live cameraPreview will be displayed cameraPreviewLayout = (FrameLayout) findViewById(id.camera_preview); cameraPreview = new CameraPreview(this); // now we add surface view to layout cameraPreviewLayout.removeAllViews(); cameraPreviewLayout.addView(cameraPreview); // get layouts prepared for different elements (views) // this is whole recording screen, as big as screen available recordingScreenLayout=(FrameLayout) findViewById(R.id.recording_screen); // this is used to display sores as they are added, it displays like a path // each score added is a new text view simply and as user undos these are removed one by one allScoresLayout=(LinearLayout) findViewById(R.id.all_scores); // layout prepared for controls like record/stop buttons etc startStopLayout=(RelativeLayout) findViewById(R.id.start_stop_layout); // set up timer so it can be turned on when needed //fightTimer=new FightTimer(this); fightTimer = (FightTimer) findViewById(id.fight_timer); // get views for displaying scores score1=(TextView) findViewById(id.score1); score2=(TextView) findViewById(id.score2); advantages1=(TextView) findViewById(id.advantages1); advantages2=(TextView) findViewById(id.advantages2); penalties1=(TextView) findViewById(id.penalties1); penalties2=(TextView) findViewById(id.penalties2); RelativeLayout welcomeScreen=(RelativeLayout) findViewById(id.welcome_screen); Animation fadeIn = AnimationUtils.loadAnimation(this, R.anim.fade_in); welcomeScreen.startAnimation(fadeIn); Toast.makeText(this,"Start ", 2000).show(); animateViews(); } Settings activity is below, after coming back from this activity surfaceview is drawn on top of other elements. public class SettingsActivity extends PreferenceActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(MyFirstAppActivity.getCamera()==null) { Toast.makeText(this,"Sorry, camera is not available",2000).show(); return; } addPreferencesFromResource(R.xml.preferences); } }

    Read the article

  • Android onClickListener options and help on creating a non-static array adapter

    - by CoderInTraining
    I am trying to make an application that gets data dynamically and displays it in a listView. Here is my code that I have with static data. There are a couple of things I want to try and do and can't figure out how. MainActivity.java package text.example.project; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import android.app.ListActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends ListActivity { //declarations private boolean isItem; private ArrayAdapter<String> item1Adapter; private ArrayAdapter<String> item2Adapter; private ArrayAdapter<String> item3Adapter; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Collections.sort(ITEM1); Collections.sort(ITEM2); Collections.sort(ITEM3); item1Adapter = new ArrayAdapter<String>(this, R.layout.list_item, ITEM1); item2Adapter = new ArrayAdapter<String>(this, R.layout.list_item, ITEM2); item3Adapter = new ArrayAdapter<String>(this, R.layout.list_item, ITEM3); setListAdapter(item1Adapter); isItem = true; ListView lv = getListView(); lv.setTextFilterEnabled(true); lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // When clicked, show a toast with the TextView text if (isItem) { //ITEM1.add("another\n\t" + Calendar.getInstance().getTime()); Collections.sort(ITEM1); item2Adapter.notifyDataSetChanged(); setListAdapter(item2Adapter); isItem = false; } else { item1Adapter.notifyDataSetChanged(); setListAdapter(item1Adapter); isItem = true; } Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show(); } }); } // need to turn dynamic static ArrayList<String> ITEM1 = new ArrayList<String> (Arrays.asList( "ITEM1-1", "ITEM1-2" )); static ArrayList<String> ITEM2 = new ArrayList<String> (Arrays.asList( "ITEM2-1", "ITEM2-2" )); static ArrayList<String> ITEM3 = new ArrayList<String> (Arrays.asList("ITEM3-1", "ITEM3-2")); } list_item.xml <?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10dp" android:textSize="16sp" > </TextView> What I want to do is first pull from a dynamic source. I need to do what is almost exactly like this tutorial... http://androiddevelopement.blogspot.in/2011/06/android-xml-parsing-tutorial-using.html ... however, I can't get the tutorial to work... I also would like to know how I can make the list item clicks so that if I click on "ITEM1-1" it goes to the menu "ITEM2-1" and "ITEM2-2". and if "ITEM1-2" is clicked, then it goes to the menu with "ITEM3-1" and "ITEM3-2"... I am totally a noob at this whole android development thing. So any suggestions would be great!

    Read the article

  • getting Null pointer exception

    - by Abhijeet
    Hi I am getting this message on emulator when I run my android project: The application MediaPlayerDemo_Video.java (process com.android.MediaPlayerDemo_Video) has stopped unexpectedly. Please try again I am trying to run the MediaPlayerDemo_Video.java given in ApiDemos in the Samples given on developer.android.com. The code is : package com.android.MediaPlayerDemo_Video; import android.app.Activity; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.MediaPlayer.OnBufferingUpdateListener; import android.media.MediaPlayer.OnCompletionListener; import android.media.MediaPlayer.OnPreparedListener; import android.media.MediaPlayer.OnVideoSizeChangedListener; import android.os.Bundle; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.widget.Toast; public class MediaPlayerDemo_Video extends Activity implements OnBufferingUpdateListener, OnCompletionListener, OnPreparedListener, OnVideoSizeChangedListener, SurfaceHolder.Callback { private static final String TAG = "MediaPlayerDemo"; private int mVideoWidth; private int mVideoHeight; private MediaPlayer mMediaPlayer; private SurfaceView mPreview; private SurfaceHolder holder; private String path; private Bundle extras; private static final String MEDIA = "media"; // private static final int LOCAL_AUDIO = 1; // private static final int STREAM_AUDIO = 2; // private static final int RESOURCES_AUDIO = 3; private static final int LOCAL_VIDEO = 4; private static final int STREAM_VIDEO = 5; private boolean mIsVideoSizeKnown = false; private boolean mIsVideoReadyToBePlayed = false; /** * * Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.mediaplayer_2); mPreview = (SurfaceView) findViewById(R.id.surface); holder = mPreview.getHolder(); holder.addCallback(this); holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); extras = getIntent().getExtras(); } private void playVideo(Integer Media) { doCleanUp(); try { switch (Media) { case LOCAL_VIDEO: // Set the path variable to a local media file path. path = ""; if (path == "") { // Tell the user to provide a media file URL. Toast .makeText( MediaPlayerDemo_Video.this, "Please edit MediaPlayerDemo_Video Activity, " + "and set the path variable to your media file path." + " Your media file must be stored on sdcard.", Toast.LENGTH_LONG).show(); } break; case STREAM_VIDEO: /* * Set path variable to progressive streamable mp4 or * 3gpp format URL. Http protocol should be used. * Mediaplayer can only play "progressive streamable * contents" which basically means: 1. the movie atom has to * precede all the media data atoms. 2. The clip has to be * reasonably interleaved. * */ path = ""; if (path == "") { // Tell the user to provide a media file URL. Toast .makeText( MediaPlayerDemo_Video.this, "Please edit MediaPlayerDemo_Video Activity," + " and set the path variable to your media file URL.", Toast.LENGTH_LONG).show(); } break; } // Create a new media player and set the listeners mMediaPlayer = new MediaPlayer(); mMediaPlayer.setDataSource(path); mMediaPlayer.setDisplay(holder); mMediaPlayer.prepare(); mMediaPlayer.setOnBufferingUpdateListener(this); mMediaPlayer.setOnCompletionListener(this); mMediaPlayer.setOnPreparedListener(this); mMediaPlayer.setOnVideoSizeChangedListener(this); mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); } catch (Exception e) { Log.e(TAG, "error: " + e.getMessage(), e); } } public void onBufferingUpdate(MediaPlayer arg0, int percent) { Log.d(TAG, "onBufferingUpdate percent:" + percent); } public void onCompletion(MediaPlayer arg0) { Log.d(TAG, "onCompletion called"); } public void onVideoSizeChanged(MediaPlayer mp, int width, int height) { Log.v(TAG, "onVideoSizeChanged called"); if (width == 0 || height == 0) { Log.e(TAG, "invalid video width(" + width + ") or height(" + height + ")"); return; } mIsVideoSizeKnown = true; mVideoWidth = width; mVideoHeight = height; if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) { startVideoPlayback(); } } public void onPrepared(MediaPlayer mediaplayer) { Log.d(TAG, "onPrepared called"); mIsVideoReadyToBePlayed = true; if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) { startVideoPlayback(); } } public void surfaceChanged(SurfaceHolder surfaceholder, int i, int j, int k) { Log.d(TAG, "surfaceChanged called"); } public void surfaceDestroyed(SurfaceHolder surfaceholder) { Log.d(TAG, "surfaceDestroyed called"); } public void surfaceCreated(SurfaceHolder holder) { Log.d(TAG, "surfaceCreated called"); playVideo(extras.getInt(MEDIA)); } @Override protected void onPause() { super.onPause(); releaseMediaPlayer(); doCleanUp(); } @Override protected void onDestroy() { super.onDestroy(); releaseMediaPlayer(); doCleanUp(); } private void releaseMediaPlayer() { if (mMediaPlayer != null) { mMediaPlayer.release(); mMediaPlayer = null; } } private void doCleanUp() { mVideoWidth = 0; mVideoHeight = 0; mIsVideoReadyToBePlayed = false; mIsVideoSizeKnown = false; } private void startVideoPlayback() { Log.v(TAG, "startVideoPlayback"); holder.setFixedSize(mVideoWidth, mVideoHeight); mMediaPlayer.start(); } } I think the above message is due to Null pointer exception , however I may be false. I am unable to find where the error is . So , Please someone help me out .

    Read the article

  • How to save/retrieve words to/from SQlite database?

    - by user998032
    Sorry if I repeat my question but I have still had no clues of what to do and how to deal with the question. My app is a dictionary. I assume that users will need to add words that they want to memorise to a Favourite list. Thus, I created a Favorite button that works on two phases: short-click to save the currently-view word into the Favourite list; and long-click to view the Favourite list so that users can click on any words to look them up again. I go for using a SQlite database to store the favourite words but I wonder how I can do this task. Specifically, my questions are: Should I use the current dictionary SQLite database or create a new SQLite database to favorite words? In each case, what codes do I have to write to cope with the mentioned task? Could anyone there kindly help? Here is the dictionary code: package mydict.app; import java.util.ArrayList; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.util.Log; public class DictionaryEngine { static final private String SQL_TAG = "[MyAppName - DictionaryEngine]"; private SQLiteDatabase mDB = null; private String mDBName; private String mDBPath; //private String mDBExtension; public ArrayList<String> lstCurrentWord = null; public ArrayList<String> lstCurrentContent = null; //public ArrayAdapter<String> adapter = null; public DictionaryEngine() { lstCurrentContent = new ArrayList<String>(); lstCurrentWord = new ArrayList<String>(); } public DictionaryEngine(String basePath, String dbName, String dbExtension) { //mDBExtension = getResources().getString(R.string.dbExtension); //mDBExtension = dbExtension; lstCurrentContent = new ArrayList<String>(); lstCurrentWord = new ArrayList<String>(); this.setDatabaseFile(basePath, dbName, dbExtension); } public boolean setDatabaseFile(String basePath, String dbName, String dbExtension) { if (mDB != null) { if (mDB.isOpen() == true) // Database is already opened { if (basePath.equals(mDBPath) && dbName.equals(mDBName)) // the opened database has the same name and path -> do nothing { Log.i(SQL_TAG, "Database is already opened!"); return true; } else { mDB.close(); } } } String fullDbPath=""; try { fullDbPath = basePath + dbName + "/" + dbName + dbExtension; mDB = SQLiteDatabase.openDatabase(fullDbPath, null, SQLiteDatabase.OPEN_READWRITE|SQLiteDatabase.NO_LOCALIZED_COLLATORS); } catch (SQLiteException ex) { ex.printStackTrace(); Log.i(SQL_TAG, "There is no valid dictionary database " + dbName +" at path " + basePath); return false; } if (mDB == null) { return false; } this.mDBName = dbName; this.mDBPath = basePath; Log.i(SQL_TAG,"Database " + dbName + " is opened!"); return true; } public void getWordList(String word) { String query; // encode input String wordEncode = Utility.encodeContent(word); if (word.equals("") || word == null) { query = "SELECT id,word FROM " + mDBName + " LIMIT 0,15" ; } else { query = "SELECT id,word FROM " + mDBName + " WHERE word >= '"+wordEncode+"' LIMIT 0,15"; } //Log.i(SQL_TAG, "query = " + query); Cursor result = mDB.rawQuery(query,null); int indexWordColumn = result.getColumnIndex("Word"); int indexContentColumn = result.getColumnIndex("Content"); if (result != null) { int countRow=result.getCount(); Log.i(SQL_TAG, "countRow = " + countRow); lstCurrentWord.clear(); lstCurrentContent.clear(); if (countRow >= 1) { result.moveToFirst(); String strWord = Utility.decodeContent(result.getString(indexWordColumn)); String strContent = Utility.decodeContent(result.getString(indexContentColumn)); lstCurrentWord.add(0,strWord); lstCurrentContent.add(0,strContent); int i = 0; while (result.moveToNext()) { strWord = Utility.decodeContent(result.getString(indexWordColumn)); strContent = Utility.decodeContent(result.getString(indexContentColumn)); lstCurrentWord.add(i,strWord); lstCurrentContent.add(i,strContent); i++; } } result.close(); } } public Cursor getCursorWordList(String word) { String query; // encode input String wordEncode = Utility.encodeContent(word); if (word.equals("") || word == null) { query = "SELECT id,word FROM " + mDBName + " LIMIT 0,15" ; } else { query = "SELECT id,content,word FROM " + mDBName + " WHERE word >= '"+wordEncode+"' LIMIT 0,15"; } //Log.i(SQL_TAG, "query = " + query); Cursor result = mDB.rawQuery(query,null); return result; } public Cursor getCursorContentFromId(int wordId) { String query; // encode input if (wordId <= 0) { return null; } else { query = "SELECT id,content,word FROM " + mDBName + " WHERE Id = " + wordId ; } //Log.i(SQL_TAG, "query = " + query); Cursor result = mDB.rawQuery(query,null); return result; } public Cursor getCursorContentFromWord(String word) { String query; // encode input if (word == null || word.equals("")) { return null; } else { query = "SELECT id,content,word FROM " + mDBName + " WHERE word = '" + word + "' LIMIT 0,1"; } //Log.i(SQL_TAG, "query = " + query); Cursor result = mDB.rawQuery(query,null); return result; } public void closeDatabase() { mDB.close(); } public boolean isOpen() { return mDB.isOpen(); } public boolean isReadOnly() { return mDB.isReadOnly(); } } And here is the code below the Favourite button to save to and load the Favourite list: btnAddFavourite = (ImageButton) findViewById(R.id.btnAddFavourite); btnAddFavourite.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Add code here to save the favourite, e.g. in the db. Toast toast = Toast.makeText(ContentView.this, R.string.messageWordAddedToFarvourite, Toast.LENGTH_SHORT); toast.show(); } }); btnAddFavourite.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { // Open the favourite Activity, which in turn will fetch the saved favourites, to show them. Intent intent = new Intent(getApplicationContext(), FavViewFavourite.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); getApplicationContext().startActivity(intent); return false; } }); }

    Read the article

  • Encrypt images before uploading to Dropbox [migrated]

    - by Cherry
    I want to encrypt a file first before the file will be uploaded to the dropbox. So i have implement the encryption inside the uploading of the codes. However, there is an error after i integrate the codes together. Where did my mistake go wrong? Error at putFileOverwriteRequest and it says The method putFileOverwriteRequest(String, InputStream, long, ProgressListener) in the type DropboxAPI is not applicable for the arguments (String, FileOutputStream, long, new ProgressListener(){}) Another problem is that this FileOutputStream fis = new FileOutputStream(new File("dont know what to put in this field")); i do not know where to put the file so that after i read the file, it will call the path and then upload to the Dropbox. Anyone is kind to help me in this? As time is running out for me and i still cant solve the problem. Thank you in advance. The full code is as below. public class UploadPicture extends AsyncTask<Void, Long, Boolean> { private DropboxAPI<?> mApi; private String mPath; private File mFile; private long mFileLen; private UploadRequest mRequest; private Context mContext; private final ProgressDialog mDialog; private String mErrorMsg; public UploadPicture(Context context, DropboxAPI<?> api, String dropboxPath, File file) { // We set the context this way so we don't accidentally leak activities mContext = context.getApplicationContext(); mFileLen = file.length(); mApi = api; mPath = dropboxPath; mFile = file; mDialog = new ProgressDialog(context); mDialog.setMax(100); mDialog.setMessage("Uploading " + file.getName()); mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mDialog.setProgress(0); mDialog.setButton("Cancel", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { // This will cancel the putFile operation mRequest.abort(); } }); mDialog.show(); } @Override protected Boolean doInBackground(Void... params) { try { KeyGenerator keygen = KeyGenerator.getInstance("DES"); SecretKey key = keygen.generateKey(); //generate key //encrypt file here first byte[] plainData; byte[] encryptedData; Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); //File f = new File(mFile); //read file FileInputStream in = new FileInputStream(mFile); //obtains input bytes from a file plainData = new byte[(int)mFile.length()]; in.read(plainData); //Read bytes of data into an array of bytes encryptedData = cipher.doFinal(plainData); //encrypt data FileOutputStream fis = new FileOutputStream(new File("dont know what to put in this field")); //upload to a path first then call the path so that it can be uploaded up to the dropbox //save encrypted file to dropbox // By creating a request, we get a handle to the putFile operation, // so we can cancel it later if we want to //FileInputStream fis = new FileInputStream(mFile); String path = mPath + mFile.getName(); mRequest = mApi.putFileOverwriteRequest(path, fis, mFile.length(), new ProgressListener() { @Override public long progressInterval() { // Update the progress bar every half-second or so return 500; } @Override public void onProgress(long bytes, long total) { publishProgress(bytes); } }); if (mRequest != null) { mRequest.upload(); return true; } } catch (DropboxUnlinkedException e) { // This session wasn't authenticated properly or user unlinked mErrorMsg = "This app wasn't authenticated properly."; } catch (DropboxFileSizeException e) { // File size too big to upload via the API mErrorMsg = "This file is too big to upload"; } catch (DropboxPartialFileException e) { // We canceled the operation mErrorMsg = "Upload canceled"; } catch (DropboxServerException e) { // Server-side exception. These are examples of what could happen, // but we don't do anything special with them here. if (e.error == DropboxServerException._401_UNAUTHORIZED) { // Unauthorized, so we should unlink them. You may want to // automatically log the user out in this case. } else if (e.error == DropboxServerException._403_FORBIDDEN) { // Not allowed to access this } else if (e.error == DropboxServerException._404_NOT_FOUND) { // path not found (or if it was the thumbnail, can't be // thumbnailed) } else if (e.error == DropboxServerException._507_INSUFFICIENT_STORAGE) { // user is over quota } else { // Something else } // This gets the Dropbox error, translated into the user's language mErrorMsg = e.body.userError; if (mErrorMsg == null) { mErrorMsg = e.body.error; } } catch (DropboxIOException e) { // Happens all the time, probably want to retry automatically. mErrorMsg = "Network error. Try again."; } catch (DropboxParseException e) { // Probably due to Dropbox server restarting, should retry mErrorMsg = "Dropbox error. Try again."; } catch (DropboxException e) { // Unknown error mErrorMsg = "Unknown error. Try again."; } catch (FileNotFoundException e) { } return false; } @Override protected void onProgressUpdate(Long... progress) { int percent = (int)(100.0*(double)progress[0]/mFileLen + 0.5); mDialog.setProgress(percent); } @Override protected void onPostExecute(Boolean result) { mDialog.dismiss(); if (result) { showToast("Image successfully uploaded"); } else { showToast(mErrorMsg); } } private void showToast(String msg) { Toast error = Toast.makeText(mContext, msg, Toast.LENGTH_LONG); error.show(); } }

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >