on Saturday, January 31, 2015


In my application all my Button have their own sound effects. I just want two button in my setting to disable and enable sound effects in whole application. I enable sound effects for each button like this:



MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.laser);
mp.start();


but how i can disable , and also i try this code:



setSoundEffectsEnabled(false);


but the point is that i just want to disable and enable sound effects by user's selection . I was wondering if anyone could suggest me any solution.




assume has an app."myapp". an service in separate process."myservice".

process=":myservice". an second service in separated service. "secondservice".



process=":myservice".


two service are

exported = "true".



inputPinCodeIntent = new Intent(context, EnterCodeActivity.class);
inputPinCodeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(inputPinCodeIntent);


in EnterCodeActivity get an code and with



Messenger messenger = new Messenger();
messenger.send(m);


send an message to "secondservice". but dont gotted message. im running service like



final Intent serviceIntent = new Intent(this, PincodeCreditionalInput.class);
bindService(serviceIntent, serviceConnection, BIND_AUTO_CREATE);


in "onStart" event. anyone can help?


thankful.




I was having some problem when trying to import zxing-core.jar into my project for QR code scanning purpose. I have some other .jar like achartengine, facebook sdk, google library all those and it was working fine until I added the zxing.jar. I am getting the error message as:



[2015-01-31 19:00:40 - eNeighbourhood] Dx
trouble writing output: already prepared
[2015-01-31 19:00:41 - Dex Loader] Unable to execute dex: Multiple dex files define Lcom/google/zxing/BarcodeFormat;
[2015-01-31 19:00:41 - eNeighbourhood] Conversion to Dalvik format failed: Unable to execute dex: Multiple dex files define Lcom/google/zxing/BarcodeFormat;


I wonder is there any way to fix this? Because if I used back the same code but for an empty project, the zxing works fine.


Thanks in advance.




I have a problem when trying to parse JSON data from localhost to fragment android using AsyncTask.


this my code FindPeopleFragment.java



public class FindPeopleFragment extends Fragment {
private ProgressDialog pDialog;
String nim;
JSONArray str_json = null;
String surl = "http://10.0.2.2/siakad/jadwal.php?nim=125410295&&jam=10:00 - 12:30";
TextView isinya;

public FindPeopleFragment(Bundle b){
nim = b.getString("par_kode");

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{

if (container == null)
{
return null;
}


View rootView = inflater.inflate(R.layout.fragment_find_people, container, false);
isinya=(TextView)rootView.findViewById(R.id.isi);

new AmbilData().execute();
return rootView;
}

class AmbilData extends AsyncTask<String, Void, JSONObject> {
String matkul;
String ruang;
String dosen;
String sks;
String jamkul;
String kelas;
String hari;

@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Sabar gan, masih ngambil data neh...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();


}

protected JSONObject doInBackground(String... result) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.AmbilJson(surl);
return json;
}


@Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
pDialog.dismiss();
try {
str_json = result.getJSONArray("jadwal");

for(int i = 0; i < str_json.length(); i++){
JSONObject ar = str_json.getJSONObject(i);

matkul= ar.getString("matkul");
sks = ar.getString("sks");
hari = ar.getString("hari");
jamkul = ar.getString("jam");
ruang = ar.getString("ruang");
kelas = ar.getString("kelas");
dosen = ar.getString("dosen");

isinya.setText("Matakuliah : "+matkul+
"\nSks : "+sks+
"\nHari : "+hari+
"\nJam : "+jamkul+
"\nRuang : "+ruang+
"\nKelas : "+kelas+
"\nDosen : "+dosen);

} catch (JSONException e) {
e.printStackTrace();
Log.e("hasil", "Failed data was:\n" + result);
}

}
}


}


and in my JSONParser.java



public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject AmbilJson(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}


And I have some errors in my LogCat :



01-31 04:25:46.900: E/AndroidRuntime(2985): FATAL EXCEPTION: AsyncTask #4
01-31 04:25:46.900: E/AndroidRuntime(2985): java.lang.RuntimeException: An error occured while executing doInBackground()
01-31 04:25:46.900: E/AndroidRuntime(2985): at android.os.AsyncTask$3.done(AsyncTask.java:299)
01-31 04:25:46.900: E/AndroidRuntime(2985): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
01-31 04:25:46.900: E/AndroidRuntime(2985): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
01-31 04:25:46.900: E/AndroidRuntime(2985): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
01-31 04:25:46.900: E/AndroidRuntime(2985): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
01-31 04:25:46.900: E/AndroidRuntime(2985): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
01-31 04:25:46.900: E/AndroidRuntime(2985): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
01-31 04:25:46.900: E/AndroidRuntime(2985): at java.lang.Thread.run(Thread.java:841)
01-31 04:25:46.900: E/AndroidRuntime(2985): Caused by: java.lang.IllegalArgumentException: Illegal character in query at index 58: http://10.0.2.2/siakad/jadwal.php?nim=125410295&&jam=10:00 - 12:30
01-31 04:25:46.900: E/AndroidRuntime(2985): at java.net.URI.create(URI.java:727)
01-31 04:25:46.900: E/AndroidRuntime(2985): at org.apache.http.client.methods.HttpPost.<init>(HttpPost.java:79)
01-31 04:25:46.900: E/AndroidRuntime(2985): at sob.akademik.JSONParser.AmbilJson(JSONParser.java:35)
01-31 04:25:46.900: E/AndroidRuntime(2985): at sob.akademik.FindPeopleFragment$AmbilData.doInBackground(FindPeopleFragment.java:164)
01-31 04:25:46.900: E/AndroidRuntime(2985): at sob.akademik.FindPeopleFragment$AmbilData.doInBackground(FindPeopleFragment.java:1)
01-31 04:25:46.900: E/AndroidRuntime(2985): at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-31 04:25:46.900: E/AndroidRuntime(2985): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
01-31 04:25:46.900: E/AndroidRuntime(2985): ... 4 more


please help me to fix this problem. thank you.




I have a class by the name G which was extended from Application, this is the class :



public class G extends Application {

public static Context ctx;
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();

ctx = this.getApplicationContext();
}
}


and in AndroidManifest.xml i added this class like this :



<?xml version="1.0" encoding="utf-8"?>
<uses-sdk android:minSdkVersion="8" />

<application
andriod:name=".G"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".DatabaseTestActivity"
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>


but it give me this error :The prefix "andriod" for attribute "andriod:name" associated with an element type "application" is not bound.


whats the problem ?




I have a game board with 5x5 squares made of canvas drawrect:



protected void onDraw(Canvas canvas) {
for (int rowNo = 0; rowNo < nSquares; rowNo++) {
paint.setColor(((rowNo & 1) == 0) ? colorA : colorB);
for (int colNo = 0; colNo < nSquares; colNo++) {
int left = colNo * squareWidth;
int top = rowNo * squareWidth;

Rect areaRect = new Rect(left, top, left + squareWidth, top + squareWidth);
canvas.drawRect(areaRect, paint);


paint.setColor((paint.getColor() == colorA) ? colorB : colorA);

paint.setTextSize((float)(squareWidth*0.8));

RectF bounds = new RectF(areaRect);
String letter = "A";
bounds.right = paint.measureText(letter, 0, letter.length());
bounds.bottom = paint.descent() - paint.ascent();

bounds.left += (areaRect.width() - bounds.right) / 2.0f;
bounds.top += (areaRect.height() - bounds.bottom) / 2.0f;

canvas.drawText(letter, bounds.left, bounds.top - paint.ascent(), paint);
}
}


I want to track touch input to get the squares the user are touching.. My attempt was



public boolean onTouchEvent(MotionEvent event){

int action = MotionEventCompat.getActionMasked(event);

int x = (int)event.getX();
int y = (int)event.getY();
Log.i(DEBUG_TAG, "Position: (" + x + ", " + y + ")");

int squareTouched = gameBoard.getSquare(x,y);
}


where getSquare is



public int getSquare(int x, int y) {
int row = 0;
int col = 0;
for(int rowNo = 1; rowNo <= nSquares; rowNo++) {
Log.i("Row", "Width: " + squareWidth + " rowNo: " + rowNo + " rowNo*squareW: " + rowNo*squareWidth + " y: " + y);
if(rowNo*squareWidth > y)
{
row = rowNo;
break;
}
}

for (int colNo = 1; colNo <= nSquares; colNo++) {
if(colNo*squareWidth > x)
{
col = colNo;
break;
}
}
Log.i(DEBUG_TAG, "Row: " + row + " Col: " + col);
return (row-1)*nSquares + col;
}


The problem is that the onTouchEvent getX and getY are referring to the screen 0,0, but when I draw the squares 0,0,0,0 is referring to the view origin? Am I right? How can I get the input position relative to the game board view? Could it be a solution to get the view position in the screen and add/subtract this to the tochEvent x- and y position?




I have this XML which contains an item list. This xml file shows the following error:



!ENTRY org.eclipse.m2e.logback.configuration 2 0 2015-01-30 00:55:29.947
!MESSAGE Exception while setting up logging:org.eclipse.osgi.internal.framework.EquinoxConfiguration$1 cannot be cast to java.lang.String
!STACK 0
java.lang.ClassCastException: org.eclipse.osgi.internal.framework.EquinoxConfiguration$1 cannot be cast to java.lang.String
at org.eclipse.m2e.logback.configuration.LogHelper.logJavaProperties(LogHelper.java:26)
at org.eclipse.m2e.logback.configuration.LogPlugin.loadConfiguration(LogPlugin.java:189)
at org.eclipse.m2e.logback.configuration.LogPlugin.configureLogback(LogPlugin.java:144)
at org.eclipse.m2e.logback.configuration.LogPlugin.access$2(LogPlugin.java:107)
at org.eclipse.m2e.logback.configuration.LogPlugin$1.run(LogPlugin.java:62)
at java.util.TimerThread.mainLoop(Unknown Source)
at java.util.TimerThread.run(Unknown Source)


In the graphic mode of this xml the message is:



Exception raised during rendering: com.android.layoutlib.bridge.MockView cannot be cast to android.view.ViewGroup
Exception details are logged in Window > Show View > Error Log
The following classes could not be found:
- item (Fix Build Path, Edit XML)
- menu (Fix Build Path, Edit XML)


My xml file is:



<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >

<item
android:id="@+id/menuSalir"
android:onClick="salirApp"
android:orderInCategory="2"
android:showAsAction="always"
android:title="@string/salir"
android:visibility="visible"/>

<item
android:id="@+id/menuVerSolicitudes"
android:icon="@drawable/ic_tab_otros"
android:onClick="abreActivitySolicitudes"
android:orderInCategory="1"
android:showAsAction="always"
android:title="@string/verSolicitudes"
android:visibility="visible"/>
</menu>


And I have tried another this without results (I've seen this solution in other questions in this forum): introduce menu in a layout.


What can be the problem? Thanks a lot.




Based on an answer on this thread, we can upload and download from FTP server:



//UPLOAD
try
{
FTPClient con = new FTPClient();
con.connect("192.168.2.57");

if (con.login("Administrator", "KUjWbk"))
{
con.enterLocalPassiveMode(); // important!
con.setFileType(FTP.BINARY_FILE_TYPE);
String data = "/sdcard/vivekm4a.m4a";

FileInputStream in = new FileInputStream(new File(data));
boolean result = con.storeFile("/vivekm4a.m4a", in);
in.close();
if (result) Log.v("upload result", "succeeded");
con.logout();
con.disconnect();
}
}
catch (Exception e)
{
e.printStackTrace();
}

//DOWNLOAD
try
{
FTPClient con = new FTPClient();
con.connect("192.168.2.57");

if (con.login("Administrator", "KUjWbk"))
{
con.enterLocalPassiveMode(); // important!
con.setFileType(FTP.BINARY_FILE_TYPE);
String data = "/sdcard/vivekm4a.m4a";

OutputStream out = new FileOutputStream(new File(data));
boolean result = con.retrieveFile("vivekm4a.m4a", out);
out.close();
if (result) Log.v("download result", "succeeded");
con.logout();
con.disconnect();
}
}
catch (Exception e)
{
Log.v("download result","failed");
e.printStackTrace();
}


In download part, is it possible to just retrieve the file (assuming the file is always jpg) and convert it to Bitmap without having to create a file in my application's folder?




i am using drag-sort-listview https://github.com/bauerca/drag-sort-list-view to sort rows of my list-view, and i have created a demo using this library, but it is not working, when i try to drag rows it is not working.



public class MainActivity extends Activity implements OnItemClickListener {

public static final String[] titles = new String[] { "Strawberry",
"Banana", "Orange", "Mixed" };

public static final String[] descriptions = new String[] {
"It is an aggregate accessory fruit",
"It is the largest herbaceous flowering plant", "Citrus Fruit",
"Mixed Fruits" };

public static final Integer[] images = { R.drawable.drag,
R.drawable.drag, R.drawable.drag, R.drawable.drag };

//ListView listView;
DragSortListView listView;
List<RowItem> rowItems;
CustomListViewAdapter adapter;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

rowItems = new ArrayList<RowItem>();
for (int i = 0; i < titles.length; i++) {
RowItem item = new RowItem(images[i], titles[i], descriptions[i]);
rowItems.add(item);
}
listView = (DragSortListView) findViewById(R.id.listview);
//listView = (ListView) findViewById(R.id.list);
final CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.list_item, rowItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
listView.setDropListener(new DropListener() {

@Override
public void drop(int from, int to) {
if (from != to) {
//DragSortListView list = getListView();
RowItem item = adapter.getItem(from);
adapter.remove(item);
adapter.insert(item, to);
listView.moveCheckState(from, to);

//Log.d("DSLV", "Selected item is " + listView.getCheckedItemPosition());
}
}
});
}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast toast = Toast.makeText(getApplicationContext(), "Item "
+ (position + 1) + ": " + rowItems.get(position),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
}


activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:dslv="http://schemas.android.com/apk/res/com.example.testingui"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<com.mobeta.android.dslv.DragSortListView
android:id="@+id/listview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:dividerHeight="5dp"
dslv:collapsed_height="2dp"
dslv:drag_enabled="true"
dslv:drag_handle_id="@drawable/drag"
dslv:drag_scroll_start="0.33"
dslv:drag_start_mode="onMove"
dslv:float_alpha="0.6"
dslv:max_drag_scroll_speed="0.5"
dslv:remove_enabled="true"
dslv:remove_mode="flingRemove"
dslv:slide_shuffle_speed="0.3"
dslv:sort_enabled="true"
dslv:track_drag_sort="true"
dslv:use_default_controller="true" />

</RelativeLayout>


CustomListViewAdapter.java



public class CustomListViewAdapter extends ArrayAdapter<RowItem> {

Context context;

public CustomListViewAdapter(Context context, int resourceId,
List<RowItem> items) {
super(context, resourceId, items);
this.context = context;
}

/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDesc;
}

public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
RowItem rowItem = getItem(position);

LayoutInflater mInflater = (LayoutInflater) context .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.descs);
holder.txtTitle = (TextView) convertView.findViewById(R.id.titles);
holder.imageView = (ImageView) convertView.findViewById(R.id.icons);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();

holder.txtDesc.setText(rowItem.getDesc());
holder.txtTitle.setText(rowItem.getTitle());
holder.imageView.setImageResource(rowItem.getImageId());

return convertView;
}
}


list_item.xml



<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="@+id/icons"
android:layout_width="80dp"
android:layout_height="80dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" />

<TextView
android:id="@+id/titles"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/icons"
android:paddingBottom="10dp"
android:textColor="#CC0033"
android:textSize="16dp" />

<TextView
android:id="@+id/descs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/titles"
android:layout_toRightOf="@+id/icons"
android:paddingLeft="10dp"
android:textColor="#3399FF"
android:textSize="14dp" />
</RelativeLayout>


RowItem.java



public class RowItem {
private int imageId;
private String title;
private String desc;

public RowItem(int imageId, String title, String desc) {
this.imageId = imageId;
this.title = title;
this.desc = desc;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public String toString() {
return title + "\n" + desc;
}
}



What is the difference between the different values of the variable LOCAL_CERTIFICATE ?


I know of two values platform and shared. What are the other possible values in Android build system ? How does it effect our application's behaviour.


LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS)


LOCAL_MODULE_TAGS := optional


LOCAL_SRC_FILES := $(call all-java-files-under, src)


LOCAL_PACKAGE_NAME := abc LOCAL_CERTIFICATE := shared


LOCAL_JNI_STATIC_LIBRARIES := abc


LOCAL_PROGUARD_ENABLED := disabled


include $(BUILD_PACKAGE)


include $(call all-makefiles-under,$(LOCAL_PATH))




I am getting the stacktrace error at runtime.



Runtime Exception : An error occured while executing doInBackground()


Fatal signal 6 (SIGABRT) at 0x0000162c (code=-6), thread 5676



I am posted the full stacktrace and pointed out the error line in below coding.


While loading the fragment page I am getting this log error.Suddenly application crashers.It has been happening in all devices.


Stacktrace:



01-30 05:05:57.213: E/dalvikvm(5676): VM aborting
01-30 05:05:57.213: A/libc(5676): Fatal signal 6 (SIGABRT) at 0x0000162c (code=-6), thread 5676 (e.quranmadeeasy)
01-30 05:05:57.761: D/dalvikvm(5767): GC_FOR_ALLOC freed 121K, 6% free 3345K/3524K, paused 2ms, total 2ms
01-30 05:05:57.761: I/dalvikvm-heap(5767): Grow heap (frag case) to 4.394MB for 1127532-byte allocation
01-30 05:05:57.761: D/dalvikvm(5767): GC_FOR_ALLOC freed <1K, 4% free 4446K/4628K, paused 2ms, total 2ms
01-30 05:05:57.805: W/dalvikvm(5767): threadid=12: thread exiting with uncaught exception (group=0xa4cc6b20)
01-30 05:05:57.805: W/dalvikvm(5767): threadid=15: thread exiting with uncaught exception (group=0xa4cc6b20)
01-30 05:05:57.805: I/Process(5767): Sending signal. PID: 5767 SIG: 9

01-30 05:05:57.805: E/AndroidRuntime(5767): FATAL EXCEPTION: AsyncTask #1
01-30 05:05:57.805: E/AndroidRuntime(5767): Process: com.qrme.quranmadeeasy, PID: 5767
01-30 05:05:57.805: E/AndroidRuntime(5767): java.lang.RuntimeException: An error occured while executing doInBackground()
01-30 05:05:57.805: E/AndroidRuntime(5767): at android.os.AsyncTask$3.done(AsyncTask.java:300)
01-30 05:05:57.805: E/AndroidRuntime(5767): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
01-30 05:05:57.805: E/AndroidRuntime(5767): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
01-30 05:05:57.805: E/AndroidRuntime(5767): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
01-30 05:05:57.805: E/AndroidRuntime(5767): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
01-30 05:05:57.805: E/AndroidRuntime(5767): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
01-30 05:05:57.805: E/AndroidRuntime(5767): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
01-30 05:05:57.805: E/AndroidRuntime(5767): at java.lang.Thread.run(Thread.java:841)
01-30 05:05:57.805: E/AndroidRuntime(5767): Caused by: java.lang.NullPointerException
01-30 05:05:57.805: E/AndroidRuntime(5767): at com.qrme.quranmadeeasy.LessonActivity$getLesson.doInBackground(LessonActivity.java:258)
01-30 05:05:57.805: E/AndroidRuntime(5767): at com.qrme.quranmadeeasy.LessonActivity$getLesson.doInBackground(LessonActivity.java:1)
01-30 05:05:57.805: E/AndroidRuntime(5767): at android.os.AsyncTask$2.call(AsyncTask.java:288)
01-30 05:05:57.805: E/AndroidRuntime(5767): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
01-30 05:05:57.805: E/AndroidRuntime(5767): ... 4 more


LessonActivity.java:



public class LessonActivity extends Activity implements OnItemClickListener {

static ArrayList<Lesson> lessonList =null ;
static ArrayList<Settings> settings = null;

@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.activity_lesson);
initialize();
listLesson.setOnItemClickListener(this);
}

@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();

new getLesson().execute("");
}

..............
..............

// Async Task for getting all lesson of a chapter

public class getLesson extends AsyncTask<String, Void, String> {

// ProgressDialog pd; // progress dialog declaration

@Override
protected String doInBackground(String... params) {

lessonList = DatabaseQueryHelper.getInstance().getLesson(chapterId); -->258th line

return null;
}

@Override
protected void onPreExecute() {
super.onPreExecute();

}

@Override
protected void onPostExecute(String result) {

if(lessonList!=null)
{
if(lessonList.size()>0)
{
al = new AdapterLesson(LessonActivity.this, lessonList);
listLesson.setAdapter(al);

}
}
}
}
}


Anyone can help me with this.Thank you.




I am trying to get my Action Bar to display an icon and not display any title while both states of the Navigation Drawer (open and closed) I read the documentation on developers android about how to modify the contents of the Action Bar when the drawer is visible. As the page said, I created an instance of ActionBarDrawerToggle and set the icon and set title to null. But still I am not able to see any icon and the app title appears as soon as I draw out the Navigation drawer. The following is the code I have used in onCreate of my activity



mToggle = new ActionBarDrawerToggle(
this,
drawerLayout,
R.string.drawer_open_or_close,
R.string.drawer_open_or_close) {

/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getActionBar().setTitle(R.string.drawer_open_or_close);
getActionBar().setIcon(R.drawable.icon_144);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}

/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActionBar().setTitle(R.string.drawer_open_or_close);
getActionBar().setIcon(R.drawable.icon_144);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};


As you can see, I have set the Action bar title to R.string.drawer_open_or_close, which is an empty string, during both completely open and completely closed state. I have set the app icon in both cases as well. What am I missing here?


Edit: I had forgotten to set the drawer toggle as DrawerListener, which I did



drawerLayout.setDrawerListener(mToggle);


Now when I open Navigation drawer, the app force closes and the log cat says java.lang.NullPointerException at



getActionBar().setTitle(R.string.drawer_open_or_close);



I has made a program that can run in emulator but cannot run in phone. I run with Nexus 5 emulator and successfully run but when I install the apk in my Nexus 5 phone, it is installed but cannot be opened (the 'open' button after install the app is unable clicked). And the app not listed in app list. But if I open a uninstaller app, my app is listed in the installer app. What should I do?




I have the following layout:ö



<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="@android:color/black"
android:gravity="center" >

<ImageView
android:id="@+id/main_gradient"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/gradient"
android:contentDescription="@string/imageview_description"
android:scaleType="centerInside" />
</RelativeLayout>


The 'gradient' image is a jpg with 400 x 400 pixels. My Screen size is 1920 x 1200. I set the Gravity of my RelativeLayout to be center and my ImageView's height and width are defined to be wrap_content. I tried scaleType="centerInside", fitCenter and so on and centerInParent="true" but nothing works. The ImageView always gets stretched to the screen size.


Why?


How can an ImageView with wrap_content Layout params take the whole screen when the content is 400 x 400. I dont get it.




I want to set memberlist value which is in asynk task method into onresume method but i am getting null value how i get this value?


this is my code.



public class IndexBar extends Activity implements OnItemClickListener {

HashMap<Character, Integer> alphabetToIndex;
static String TAG = "IndexBar";
int number_of_alphabets = -1;
static IndexBarHandler handler;
private EditText editsearch;
private ArrayAdapter<String> adapter1;
public ArrayAdapter<String> mainadapter;
public ArrayList<String> memberlist;
public ArrayList<String> first;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.indexbarlayout);
editsearch = (EditText) findViewById(R.id.textview_header);
editsearch.addTextChangedListener(new TextWatcher() {


@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
mainadapter.getFilter().filter(s.toString());
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub

}

@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub

}
});
getScreenHeight(this);
getScreenWidth(this);
handler = new IndexBarHandler(this);

}

protected void onResume() {
super.onResume();

/* populating the base listview */
CustomListView mainlistview = (CustomListView) findViewById(R.id.listView_main);
String main_list_array[] = getResources().getStringArray(
R.array.base_array);
if (main_list_array == null) {
Log.d(TAG, "Array of the main listview is null");
return;
}
mainadapter = new ArrayAdapter<String>(
getBaseContext(), R.layout.mainlistview_row/*
* android.R.layout.
* simple_list_item_1
*/,
main_list_array);
mainlistview.setAdapter(mainadapter);
populateHashMap();

}

public int convertDipToPx(int dp, Context context) { // 10dp=15px
Resources r = context.getResources();
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
r.getDisplayMetrics());
return (int) px;
}

public int convertPxtoDip(int pixel) { // 15px=23dp
float scale = getResources().getDisplayMetrics().density;
int dips = (int) ((pixel / scale) + 0.5f);
return dips;
}

/**
* Determines the width of the screen in pixels
*
* @return width
*/
public int getScreenWidth(Activity activity) {
Display display = activity.getWindowManager().getDefaultDisplay();
int width = display.getWidth();
Log.d(TAG, "Screen Width in pixels=" + width);
return width;
}

/**
* Determines the height of the screen in pixels
*
* @return height
*/
public int getScreenHeight(Activity activity) {
Display display = activity.getWindowManager().getDefaultDisplay();
int height = display.getHeight();
Log.d(TAG, "Screen Height in pixels=" + height);
return height;
}

public float pixelsToSp(Context context, Float px) {
float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
Log.d(TAG, "GetTextSize in pixels=" + px + " In Sp="
+ (px / scaledDensity));
return px / scaledDensity;
}

public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {

if (!(view instanceof TextView || view == null))
return;
TextView rowview = (TextView) view;

CharSequence alpahbet = rowview.getText();

if (alpahbet == null || alpahbet.equals(""))
return;

String selected_alpahbet = alpahbet.toString().trim();
Integer position = alphabetToIndex.get(selected_alpahbet.charAt(0));
Log.d(TAG, "Selected Alphabet is:" + selected_alpahbet
+ " position is:" + position);

ListView listview = (ListView) findViewById(R.id.listView_main);
listview.setSelection(position);
}

/**
* This populates the HashMap which contains the mapping between the
* alphabets and their relative position index.
*/
private void populateHashMap() {
alphabetToIndex = new HashMap<Character, Integer>();
String base_list[] = getResources().getStringArray(R.array.base_array);
int base_list_length = base_list.length;

for (int i = 0; i < base_list_length; i++) {
char firstCharacter = base_list[i].charAt(0);
boolean presentOrNot = alphabetToIndex.containsKey(firstCharacter);
if (!presentOrNot) {
alphabetToIndex.put(firstCharacter, i);
// Log.d(TAG,"Character="+firstCharacter+" position="+i);
}
}
number_of_alphabets = alphabetToIndex.size(); // Number of enteries in
// the map is equal to
// number of letters
// that would
// necessarily display
// on the right.

/*
* Now I am making an entry of those alphabets which are not there in
* the Map
*/
String alphabets[] = getResources().getStringArray(
R.array.alphabtes_array);
int index = -1;

for (String alpha1 : alphabets) {
char alpha = alpha1.charAt(0);
index++;

if (alphabetToIndex.containsKey(alpha))
continue;

/*
* Start searching the next character position. Example, here alpha
* is E. Since there is no entry for E, we need to find the position
* of next Character, F.
*/
for (int i = index + 1; i < 26; i++) { // start from next character
// to last character
char searchAlphabet = alphabets[i].charAt(0);

/*
* If we find the position of F character, then on click event
* on E should take the user to F
*/
if (alphabetToIndex.containsKey(searchAlphabet)) {
alphabetToIndex.put(alpha,
alphabetToIndex.get(searchAlphabet));
break;
} else if (i == 25) /*
* If there are no entries after E, then on
* click event on E should take the user to
* end of the list
*/
alphabetToIndex.put(alpha, base_list_length - 1);
else
continue;

}//
}//
}
public void getAllMember() {

new AsyncTask<Void, Void, String>() {
ProgressDialog mProgressDialog;
CustomListView mainlistview = (CustomListView) findViewById(R.id.listView_main);
public String firstname;

protected void onPostExecute(String result) {
mProgressDialog.dismiss();
memberlist = new ArrayList<String>();
first = new ArrayList<String>();

try {
JSONObject jsob = new JSONObject(result.toString());
if (jsob.getString("msg").equalsIgnoreCase("Success")) {
JSONArray datajson = jsob.getJSONArray("data");
for (int i = 0; i < datajson.length(); i++) {

JSONObject c = datajson.getJSONObject(i);
String id = c.getString("iMember_id");
firstname = c.getString("vUsername");
Log.d("firstname val", firstname);

memberlist.add(firstname);

}
mainadapter = new ArrayAdapter<String>(
getBaseContext(),
R.layout.mainlistview_row/*
* android.R.layout.
* simple_list_item_1
*/, memberlist);
mainlistview.setAdapter(mainadapter);

} else {
System.out.println("not a valid user");
}

} catch (Exception e) {
Log.e("login problem", "" + e);

}

}

private void startActivity(Intent i) {
// TODO Auto-generated method stub

}

@Override
protected String doInBackground(Void... arg0) {
// Creating service handler class instance
try {
HttpPost httppost1 = null;
HttpClient httpclient1 = new DefaultHttpClient();

httppost1 = new HttpPost(JsonKey.MAIN_URL);

// Add your data
List<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>(
1);
nameValuePairs1.add(new BasicNameValuePair("action",
"GetAllMembers"));
httppost1.setEntity(new UrlEncodedFormEntity(
nameValuePairs1));
// Execute HTTP Post Request
HttpResponse response1 = httpclient1.execute(httppost1);
BufferedReader in1 = new BufferedReader(
new InputStreamReader(response1.getEntity()
.getContent()));
StringBuffer sb1 = new StringBuffer("");
String line1 = "";
while ((line1 = in1.readLine()) != null) {
sb1.append(line1);
}
in1.close();
Log.e(" Get All magazine original data", sb1.toString());
return sb1.toString();
} catch (Exception e) {
Log.e("Get All magazine response problem", "" + e);
return " ";
}
}

@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
mProgressDialog = new ProgressDialog(IndexBar.this);
mProgressDialog.setTitle("");
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.setMessage("Please Wait...");
mProgressDialog.show();

}
}.execute();

}


}


the value of memberlist in getallmember is i want to set in
mainadapter = new ArrayAdapter<String>(
getBaseContext(), R.layout.mainlistview_row/*
* android.R.layout.
* simple_list_item_1
*/,
main_list_array);


in above code in place of main_array_list but doing so i am getting null pointer exception how i get this value?




Does the Deezer SDK offer the posibility to play local files on the device within the Deezer app?


If they do, is there a code example?




The question is pretty much in the title. I want to know if I can start and execute an AsyncTask or something else in the background with the Intent data from the activity, without actually launching the activity. I looked for some information, but the only thing I found is how to register a service with your app, which isn't really what I was looking for. Bonus question: can I also display a notification or a small disappearing textbox on the display upon the AsyncTask completion/addition


Thanks a lot in advance




In my app sharing bitmap to facebook .Link,description,message and imageurl all posting the facebook well but bitmap not share to facebook. I am using the following code:



Bitmap bi = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.JPEG, 20, baos);
byte[] data = baos.toByteArray();



if ( friend_uid != null ) {
final Activity activity = SocialSharingActivity.this;
Bundle params = new Bundle();
params.putString("name", "pictabsample");
params.putByteArray("picture",data);
//// params.pu
params.putString("to", friend_uid);
//
WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(SocialSharingActivity.this, Session.getActiveSession(), params))
.setOnCompleteListener(new OnCompleteListener() {

@Override
public void onComplete(Bundle values,
FacebookException error) {

}}).build();
feedDialog.show();
}


where i done mistake didn't findout.please tell me anyone known advance thanks to all




I have the following code:



locale = new Locale(loc);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
Resources resources = getResources();
resources.updateConfiguration(config, resources.getDisplayMetrics());
Intent intent = new Intent(getActivity(), Settings.class);
getActivity().finish();
startActivity(intent);


In my Preference settings screen, I obtain the value of ListPreference and onChange of the value the above code snippet is called.


However, the call happens, but the strings don't change to "ta" language. This is done inside a PreferenceFragment which is called by Settings Activity.


Text within the app changes the language to appropriate one, but the text on the toolbar doesn't change.


Can someone guide?




I want to live stream a video from hadoop(HDFC) to android. How can i do this ? I am using Xuggler for storing video on hadoop. Does Xuggler works in android ? If not, what else can help me ?




I am developing a game


First of all my game will be very simple, so i would prefer not to use libraries or opengl or canvas, i would prefer to achieve this with simple imageviews or normal views, or at least by the simplest way possible. For example with android bitmap tile mode:



public static void setBackground(Bitmap bmp, ViewGroup layout){
BitmapDrawable bitmapDrawable = new BitmapDrawable(bmp);
bitmapDrawable.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
layout.setBackgroundDrawable(bitmapDrawable);
}


I want to develop a simple 2D/3D hybrid spaceship game. The screen will be the vision from the spaceship cockpit, and you will move the spaceship touching a joystick that i have allready done. So the background will be a universe background, i mean a huge black image with stars, and this image must be moved to all directions with the joystick simulating that the spaceship is changing it's direction, and when you move a lot to the right for example, the background image must start from the begining to simulate that the space ship is still moving to the right without any limitation


As i have mentioned, i have the joystick now, and i know how to move a imageview with the joystick, the problem is that i dont know how to create a infinite imageview with tiles correctly, because when i move the background containing the tile imagedrawable then the image dissapears from the screen.


This is an example of an image for using with the infinite background:


enter image description here





This question already has an answer here:




I have a function that's saving a string, and I want that this function will run another one. this is my code:



public static String IsLoggedIn() {
new Thread(new Runnable() {
@Override
public void run() {
String cookies = CookieManager.getInstance().getCookie(getUrl);
BasicCookieStore lCS = getCookieStore(cookies, "klh-dev.com");
HttpContext localContext = new BasicHttpContext();
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.setCookieStore(lCS);
localContext.setAttribute(ClientContext.COOKIE_STORE, lCS);

HttpGet get = new HttpGet("http://klh-dev.com/lehava/lehava/system/isloggedin.php");

try {
result=httpclient.execute(get,localContext);
response_str = EntityUtils.toString(result.getEntity());
System.out.println(response_str);
UpdateMenu(); //This is the line I'm trying to add
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
return response_str;
}
public void UpdateMenu() {

mTitle = mDrawerTitle = getTitle();
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);

if (isUserLoggedIn.equals("0")) {
Arrays.copyOfRange(mPlanetTitles, 0, 2);
}

mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));

}


In the try I'm trying to add UpdateMenu(); but it's not working. The error is: Cannot make a static reference to the non-static method UpdateMenu() from the type MainActivity


Thank you for helping!




I'm trying to insert data from a spinner into a database. A beginner in Android so help will be appreciated. Here's the function:



public JSONObject order(Spinner name, String email, String password){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", order_tag));
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));

// getting JSON Object
JSONObject json = jsonParser.getJSONFromUrl(orderURL, params);
// return json
return json;
}


The error i get on params.add(new BasicNameValuePair("name", name)); is


"The constructor BasicNameValuePair(String, Spinner) is undefined, One quick fix available. Change type of name to String".




I want to trace purchase by specific user. Is there way to get purchases for user that is loged in app, not on device? In documentation says:


"The Google Play service returns only the purchases made by the user account that is currently logged in to the device. If the request is successful, the returned Bundle has a response code of 0. The response Bundle also contains a list of the product IDs, a list of the order details for each purchase, and the signatures for each purchase."


Maybe to use Manager Account?


Any help is usefull. Thanks.




I want to send multiple images those are present in my internal storage and when i selects that folder i want upload that folder into google drive. i have tried this google drive api for android https://developers.google.com/drive/android/create-file and i have used the below code but it shows some error in getGoogleApiClient


the code is



ResultCallback<DriveContentsResult> contentsCallback = new
ResultCallback<DriveContentsResult>() {
@Override
public void onResult(DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
// Handle error
return;
}

MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
.setMimeType("text/html").build();
IntentSender intentSender = Drive.DriveApi
.newCreateFileActivityBuilder()
.setInitialMetadata(metadataChangeSet)
.setInitialDriveContents(result.getDriveContents())
.build(getGoogleApiClient());
try {
startIntentSenderForResult(intentSender, 1, null, 0, 0, 0);
} catch (SendIntentException e) {
// Handle the exception
}
}
}


is there any approach to send images to drive or gmail?




i have ArrayList with multiple value. i want to change this ArrayList into String to save in sharedPreferences. then want to retrieve the String and convert it back to ArrayList


Please Help


or Please tell any Other idea to store and retrieve ArrayList




I faced with a weird problem. I have an android application and it contains activity that includes ListViewAdapter. Each element contains a checkbox. And i have the following code:



public View getView(final int position, View convertView, ViewGroup parent) {

CheckBox checkbox = (CheckBox)v.findViewById(R.id.checkbox);
checkbox.setChecked(checked[position]);

checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener(){

public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// some code
}
});

}


And when i scroll my listview down my OnCheckedChangeListener fires and reset my checkbox if it was set. Why does it happend? I excpeted OnCheckedChangeListener will be triggered when i click checkbox manually or call setChecked programmatically but it does when i scroll down too. Why?




I am using OpenFL to build an Android app to distribute on Google Play. I want to target only armv7 devices, and I believe OpenFL does armv7-only builds by default.


However when building the OpenFL build system creates and populates the libs/armeabi folder instead of a libs/armeabi-v7a folder. The problem with this is that this makes Google Play believe that the resulting apk supports armv5/armv6/armv7 when in reality it only supports armv7. This means my apps get some 1-star reviews from people with the older/incompatible devices.


On this Github issue, Joshua Granick (jgranick) explains why the build tools do this:



Oh and BTW, originally we tried only armeabi-v7, but it failed to run on certain devices. This is why there's the current behavior or using armeabi, and adding armeabi-v7 only if there is an armv5/6 version too



I would like to know what the issue he mentions is, and what devices/Android versions it would affect. Depending on what it is, it may be possible to still just do an armv7 build and manually blacklist the buggy devices.


A final option is to simply support the armv5/armv6 devices by doing a "fat" build, or by only building for armv5 which I assume is compatible everywhere. This is quite easy using the <architecture> tag in the project.xml file. It's a tradeoff I may take if there is no way to work around the problem Joshua mentioned.


Also using the Google Play developer dashboard I could also blacklist armv5/armv6 devices manually, but it would be very time consuming to do this for every app/apk.


Also for reference here are the relevant Google Play apk details I get when I build armv7-only:


google play armeabi


Thanks!




I am quite new to programming Android (7 months), and I am having a problem with creating an app. What I am trying to do is create a "Person Detail" test app for my own Android learning, by having EditText on the Main Activity with TextViews next to them (displaying default values at first), open up another activity called EditData (with a button on the main) which displays the values the user entered into the EditText (via Parcelable), return back to the Main Activty (via another button) and have those entered values displayed in the TextViews next to the EditText (upon a "Update Info" button click) instead of the default ones. I have managed to get everything working right except for displaying the changed values. Everything checks out, no errors in LogCat, but when the user / I clicks the update button, what shows are the default values. Can someone help me? Here is my Main Activity code:



import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
final Person firstPerson = new Person();
TextView displayName, displayAge, displayHeight, displayWeight;
EditText editName, editAge, editHeight, editWeight;
Button editActivity, update;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
instantiateUi();
editActivity.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
firstPerson.setPersonName(editName.getText().toString());
firstPerson.setPersonAge(Integer.parseInt(editAge.getText().toString()));
firstPerson.setPersonHeight(Integer.parseInt(editHeight.getText().toString()));
firstPerson.setPersonWeight(Integer.parseInt(editWeight.getText().toString()));
Intent editIntent = new Intent(MainActivity.this, EditData.class);
editIntent.putExtra("First_Person_Data", firstPerson);
MainActivity.this.startActivity(editIntent);
}
});
update.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
displayName.setText(firstPerson.getPersonName());
displayAge.setText(String.valueOf(firstPerson.getPersonAge()));
// String.valueOf is needed to set int for TextViews
displayHeight.setText(String.valueOf(firstPerson.getPersonHeight()));
displayWeight.setText(String.valueOf(firstPerson.getPersonWeight()));
}
});
}

private void instantiateUi() {
editName = (EditText)findViewById(R.id.edit_name);
editAge = (EditText)findViewById(R.id.edit_age);
editHeight = (EditText)findViewById(R.id.edit_height);
editWeight = (EditText)findViewById(R.id.edit_weight);
displayName = (TextView)findViewById(R.id.display_name);
displayAge = (TextView)findViewById(R.id.display_age);
displayHeight = (TextView)findViewById(R.id.display_height);
displayWeight = (TextView)findViewById(R.id.display_weight);
editActivity = (Button)findViewById(R.id.edit_activity);
update = (Button)findViewById(R.id.update_info);

}


@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, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
}


My EditData activity code:



import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;


public class EditData extends ActionBarActivity {
TextView changedName, changedAge, changedHeight, changedWeight;
Button MainActivity;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_activity);
Person incomingObject = getIntent().getParcelableExtra("First_Person_Data");
instantiateUi();
changedName.setText(incomingObject.getPersonName());
changedAge.setText(String.valueOf(incomingObject.getPersonAge()));
changedHeight.setText(String.valueOf(incomingObject.getPersonHeight()));
changedWeight.setText(String.valueOf(incomingObject.getPersonWeight()));
MainActivity.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent EditActivity = new Intent(EditData.this, MainActivity.class);
EditData.this.startActivity(EditActivity);
}
});
}

private void instantiateUi() {
changedName = (TextView)findViewById(R.id.changed_name);
changedAge = (TextView)findViewById(R.id.changed_age);
changedHeight = (TextView)findViewById(R.id.changed_height);
changedWeight = (TextView)findViewById(R.id.changed_weight);
MainActivity = (Button)findViewById(R.id.main_activity);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.edit_data_menu, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}


And my Parcelable class used for transferring data values:



import android.os.Parcel;
import android.os.Parcelable;

public class Person implements Parcelable{
String personName;
int personAge, personHeight, personWeight;

public Person(){
personName = "No Name!";
personAge = 0;
personHeight = 0;
personWeight = 0;
}

public Person(String pName, int pAge, int pHeight, int pWeight) {
personName = pName;
personAge = pAge;
personHeight = pHeight;
personWeight = pWeight;
}

public Person(Parcel in) {
personName = in.readString();
personAge = in.readInt();
personHeight = in.readInt();
personWeight = in.readInt();
}

public String getPersonName() {
return personName;
}

public void setPersonName(String personName) {
this.personName = personName;
}

public int getPersonAge() {
return personAge;
}

public void setPersonAge(int personAge) {
this.personAge = personAge;
}

public int getPersonHeight() {
return personHeight;
}

public void setPersonHeight(int personHeight) {
this.personHeight = personHeight;
}

public int getPersonWeight() {
return personWeight;
}

public void setPersonWeight(int personWeight) {
this.personWeight = personWeight;
}

@Override
public int describeContents() {
return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(personName);
dest.writeInt(personAge);
dest.writeInt(personHeight);
dest.writeInt(personWeight);
}

public static final Parcelable.Creator<Person> CREATOR =
new Parcelable.Creator<Person>() {
@Override
public Person createFromParcel(Parcel in) {
return new Person(in);
}

@Override
public Person[] newArray(int size) {
return new Person[size];
}
};
}


Sorry if there are problems, this is my first question and I would very much appreciate what help you can give to a noob C0D3R :P




I use encrypt(byte) code for input String and then save encrypt(String) in DB.


I get String encrypt from DB to decrypt it, but I need to cast String to byte without changing because decrypt get just byte.


I used s.getBytes(); but it changed it,


I need some code to cast string to byte without changing the String. Thank you so much.




I am developing an app in which i require to share data between different activities.For eg For filling a sign up form i am using 5-6 activities so by what procedure i should share the data between activities either shared Pref or staic arrayList




i am developing android app in which we take some user information and capture signature and when we click share button it wii store in database and send email....but my app after store database app is stopped and does not send mail....thanks in advance


mShare.setOnClickListener(new OnClickListener() {



public void onClick(View v)
{
//mSignature.save(mView);

new CreateNewInformation().execute();
//sendmail();
Bitmap icon = mBitmap;

//Protected void sendmail();
String TO []= {Email.getText().toString(),"sourabhkabra960@gmail.com"};


// Intent shareIntent = new shareIntent();
Intent shareIntent = new Intent(Intent.ACTION_SEND);
//shareIntent.putExtra(Intent.EXTRA_EMAIL,Address);
//shareIntent.putExtra(Intent.EXTRA_EMAIL,TO);
//shareIntent.putExtra(Intent.EXTRA_EMAIL,Address);
shareIntent.putExtra(Intent.EXTRA_SUBJECT,Name.getText().toString());
shareIntent.putExtra(Intent.EXTRA_TEXT,"amount recived="+AmtRec.getText().toString());

// shareIntent.putExtra(Intent.EXTRA_STREAM,Uri.fromFile(mypath)); //optional//use this when you want to send an image
shareIntent.setType("Text");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "Gmail"));
PackageManager pm = v.getContext().getPackageManager();
List<ResolveInfo> activityList = pm.queryIntentActivities(shareIntent, 0);
for (final ResolveInfo app : activityList)
{
if ((app.activityInfo.name).contains("android.gm"))
{
final ActivityInfo activity = app.activityInfo;
final ComponentName name = new ComponentName(activity.applicationInfo.packageName, activity.name);
// shareIntent.addCategory(Intent.CATEGORY_LAUNCHER);
//shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
shareIntent.setComponent(name);
v.getContext().startActivity(shareIntent);
break;
}
}


// share = new Intent(Intent.ACTION_SEND)
shareIntent.setType("image/png");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
icon.compress(Bitmap.CompressFormat.PNG, 100, bytes);

File f = new File(Environment.getExternalStorageDirectory() + "/" + getResources().getString(R.string.external_dir) + "/" +current);
try {
mypath.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
}
catch (IOException e) {
e.printStackTrace();
}




//shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
//startActivity(Intent.createChooser(shareIntent, "Share Image"));
}
});



How can I change typeface of dialogMessage of EditTextPreference in Android?


I want to change the default font style of the dialog, but I don't know how do it!


this is my Custom EditTextPreference:



public class MyEditTextPreferences extends EditTextPreference {

public MyEditTextPreferences(Context context) {
super(context);
}


public MyEditTextPreferences(Context context, AttributeSet attrs) {
super(context, attrs);
}


public MyEditTextPreferences(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}


@Override
protected void onBindView(View view) {
super.onBindView(view);
TextView titleView = (TextView) view.findViewById(android.R.id.title);
TextView summaryView = (TextView) view.findViewById(android.R.id.summary);
titleView.setTypeface(G.yekanfont);
summaryView.setTypeface(G.yekanfont);

}
}


and this:



<com.mydomain.mypackagename.MyEditTextPreferences
android:defaultValue="300"
android:dialogMessage="some text"
android:dialogTitle="some other text"
android:inputType="number"
android:key="DURATION_BETWEEN"
android:title="some text"
android:summary="some other text"
/>



I am having problem with the new update AS 1.1 Beta 2, Android Studio seems to stay as executing task, My always solution is restart(alt+ctr+delete) the IDE and for at least 2 - 3 runs its back again(stays on executing task).


Is there any way that i could fallback to previous version? or should I uninstall and install Android studio?


Thanks




I have ListView with custom adapter. Listview is not clickable but setOnItemLongClickListener worked properly. ListView row.xml is below:



<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="1" >

<ImageView
android:id="@+id/ivTourImage"
android:layout_width="120dp"
android:layout_height="match_parent" />

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:weightSum="1">

<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:orientation="horizontal"
android:weightSum="1">

<TextView
android:id="@+id/lblTourName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:text="Tour Name" />

<RatingBar
android:id="@+id/ratingBarTourStarCount"
style="@style/hotelRatingBarSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:focusable="false"
android:isIndicator="true"
android:numStars="5"
android:stepSize="1.0" />
</RelativeLayout>

<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:orientation="horizontal"
android:weightSum="1">

<TextView
android:id="@+id/lblPlace"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:text="Place" />

<TextView
android:id="@+id/lblPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:background="#b6fffa12"
android:text="Price"
android:textColor="#ff4770ff" />
</RelativeLayout>

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:orientation="horizontal"
android:weightSum="1">

<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="16dp"
android:src="@drawable/adult_icon_16x16" />

<TextView
android:id="@+id/lblAdultCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Adult" />

<ImageView
android:id="@+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="16dp"
android:layout_marginLeft="15dp"
android:src="@drawable/children_icon_16x16" />

<TextView
android:id="@+id/lblChildCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Child" />

<ImageView
android:id="@+id/imageView3"
android:layout_width="wrap_content"
android:layout_height="16dp"
android:layout_marginLeft="15dp"
android:src="@drawable/meal_icon_16x16" />

<TextView
android:id="@+id/lblMealCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Meal" />
</LinearLayout>


</LinearLayout>


ListView usage:



<LinearLayout
android:id="@+id/tabTourList"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>

<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/listViewTourAnounce"
android:layout_gravity="center"/>

</LinearLayout>


How to make my listview clickable? Please help me




I'm using Parse api for my application. I got this exception from some users ( about 1 out of 1000) I searched a lot and didn't find any solution relevant to this error, The Exception throws when calling Parse.initialize :



java.lang.VerifyError: com/parse/ManifestInfo
at com.parse.Parse.allParsePushIntentReceiversInternal(SourceFile:197)
at com.parse.Parse.initialize(SourceFile:134)
at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1025)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4551)
at de.robv.android.xposed.XposedBridge.invokeOriginalMethodNative(Native Method)
at de.robv.android.xposed.XposedBridge.handleHookedMethod(XposedBridge.java:631)
at android.app.ActivityThread.handleBindApplication(Native Method)
at android.app.ActivityThread.access$1500(ActivityThread.java:163)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5335)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
at dalvik.system.NativeStart.main(Native Method)


why this exception occurs for only few users? could it be something to do with Parse.com servers ?


thanks.





String items={shoporder=shop1,shopname=abc,place=mmm};


I want to split the items as like (shop1).And assign to another string



String1=shop1
string2=abc
string3=mmm


// Get User records from SQLite DB
ArrayList<HashMap<String, String>> userList = controller.getAllUsers();
// If users exists in SQLite DB
if (userList.size() != 0) {
// Set the User Array list in ListView
final ListAdapter adapter = new SimpleAdapter(second.this, userList, R.layout.view_user_entry, new String[] {
"shopId", "shopOrder","date","todayTarget","targetCompleted","shopHandled_person","shopName","salesmanName" }, new int[]
{ R.id.shopId,R.id.shopOrder,R.id.date,R.id.todayTarget,R.id.targetCompleted,R.id.shopHandled_person,R.id.shopName,R.id.salesmanName});
final ListView myList = (ListView) findViewById(android.R.id.list);
myList.setAdapter(adapter);
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

String items=myList.getItemAtPosition(position).toString();
}


The string items contains all the list values.So i want to split the values and passed in to second activity.




My app deals with itineraries and distances between cities. Because some itineraries match with more than one cities, an ArrayListArrayListString is creating with duplicate items-itineraries. Few lines below i need to assign distances to that duplicate itineraries. Here comes the problem...I can't assign different distances to that duplicate objects. I thought that different position differentiates those duplicate items...Is there any way to differentiate them; I tried with ArrayListHashmapString with no results. Any idea;




I'm new to android, but I found an app that would go great with a web scraper that I've been working very hard on and filled a database with. This is a basic app that retrieves values from a MySQL database using a PHP script and displays them on your android device.


here is the PHP:



<?php
try {
$conn = new PDO('mysql:host=localhost;dbname=beanbag', **********, ********);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}

$sql=mysql_query("select * from Recipes");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>


The original code used mysql_connect but I implemented PDO instead.


Here is the Java:



protected void onPostExecute(Void v) {

// ambil data dari Json database
try {
JSONArray Jarray = new JSONArray(result);
for(int i=0;i<Jarray.length();i++)
{
JSONObject Jasonobject = null;
//text_1 = (TextView)findViewById(R.id.txt1);
Jasonobject = Jarray.getJSONObject(i);

//get an output on the screen
//String id = Jasonobject.getString("id");
String name = Jasonobject.getString("Title");
String db_detail="";

if(et.getText().toString().equalsIgnoreCase(name)) {
db_detail = Jasonobject.getString("ingredient");
text.setText(db_detail);
break;
}
//text_1.append(id+"\t\t"+name+"\t\t"+password+"\t\t"+"\n");

}
this.progressDialog.dismiss();

} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error parsing data "+e.toString());
}
}


I can't post pics yet but Logcat says this:


JSONException: Value of type java.lang.String cannot be converted to JSONObject


Thanks for any time you would spend on this. Many other people in the comments section on the tekart blog are getting this same error but there hasn't been a good solution posted. I tried using {left brace and }right brace solution from this stackoverflow question, but I don't think that's it. I'm gaining a lot of confidence in my programming skills, but I hit a wall with this problem. Let me know if I need to post any more code or anything. Thanks again!




I want to have the following layout :


my layout


But when I run the code the first linear layout which contains a relative layout and an image is shown correctly. Then there is the "view pager" but it is not on the screen. and then there is a text box and a button which are there too.


So why my view pager is missing?



<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical"
tools:ignore="NestedWeights,ContentDescription" >

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="5" >

<ImageView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3"
android:src="@drawable/sp_page_name"
tools:ignore="ContentDescription" />

<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:padding="@dimen/product_views_horizontal_padding"
tools:ignore="NestedWeights" >
</RelativeLayout>
</LinearLayout>

<android.support.v4.view.ViewPager
android:id="@+id/pager_sharepoint"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:contentDescription="@string/TODO"/>

<TextView
android:id="@+id/sharepoint_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/sharepoint_description"
tools:ignore="SelectableText" />
<ImageButton
android:id="@+id/sp_more_info"
android:layout_width="70dp"
android:layout_height="30dp"
android:background="@drawable/more_info_icon"
android:layout_gravity="left"
android:onClick="sp_more"/>

</LinearLayout>
</ScrollView>



More generally: we aim to access the part of the code within the NFC that selects what is being transferred and change it so we can make a directory to a list within an existing application and transfer info from that list




I need to display the HttpEntity response values in the listview Here is my code



@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
// we will using AsyncTask during parsing
new AsyncTaskParseJson().execute();
}

// you can make this class as another java file so it will be separated from your main activity.
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {

final String TAG = "AsyncTaskParseJson.java";

// contacts JSONArray
JSONArray dataJsonArr = null;

@Override
protected void onPreExecute() {}

@Override
protected String doInBackground(String... arg0) {
// post the specific format data to json url
Here am getting the response values

try {
HttpClient httpClient = new DefaultHttpClient();
JSONObject object = new JSONObject();
object.put("Username", "testUser@123");
object.put("Password", "testPassword@123");
JSONObject jsonObject = new JSONObject();
jsonObject.put("Authentication", object);
jsonObject.put("RequestType", 4);
HttpPost postMethod = new HttpPost("url");
postMethod.setEntity(new StringEntity(jsonObject.toString()));
postMethod.setHeader("Accept", "application/json");
postMethod.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(postMethod);
HttpEntity entity = response.getEntity();
String response_value = EntityUtils.toString(entity).toString();
// Log.e(TAG, response_value ); //display the output in logcat

if (entity != null) {
//Convert String to JSON Object
JSONObject result = new JSONObject(response_value);

JSONArray tokenList = result.getJSONArray("Files");


for(int i=0;i<=tokenList.length();i++)
{
JSONObject oj = tokenList.getJSONObject(i);
JSONObject oj1 = (JSONObject) tokenList.getJSONObject(i).get("Borrower");
JSONObject oj2 = (JSONObject) tokenList.getJSONObject(i).get("CoBorrower");
JSONObject oj3 = (JSONObject) tokenList.getJSONObject(i).get("LoanDetails");
JSONObject oj4 = (JSONObject) tokenList.getJSONObject(i).get("PropertyAddress");
String fileid = oj.getString("FileID");
String borrowername = oj1.getString("FirstName");
String coborrowername = oj2.getString("FirstName");
String loannumber = oj3.getString("LoanNumber");
String addrs1 = oj4.getString("Address1");
String city = oj4.getString("City");
Log.e(TAG, fileid + "/" + borrowername + "/"+ coborrowername + "/"+ addrs1 + "/"+ city + "/"+ loannumber );
JSONArray orders = oj.getJSONArray("Orders");

for(int n=0;n<orders.length();n++){

JSONObject oj5 = orders.getJSONObject(n);
String appid = oj5.getString("ApplicationOrderId");
String appid1 = oj5.getString("DueDate");
Log.e(TAG, appid +"/"+ appid1);


}
}

}


} catch (Exception e) {
e.printStackTrace();
}
return null;
}

@Override
protected void onPostExecute(String strFromDoInBg) {}
}


} Now am displaying the response value in the log cat but i want to display this values in the List View. If you have any idea please help me, thanks in advance.