[Q] How to get a Reference ID to accept a variable input? - Android Q&A, Help & Troubleshooting

Hi, I'm trying to create an application, and i require to use a variable input for a reference ID to display different arrays here is what i am using at the moment
Code:
public void verbTenses() {
Spinner verbs = (Spinner) findViewById(R.id.verbs);
Spinner tenses = (Spinner) findViewById(R.id.verb_tenses);
[COLOR="Blue"]ListAdapter adapter = R.array.(verbs.getSelectedItem() + "_" + tenses.getSelectedItem());[/COLOR]
ListView list = (ListView) findViewById(R.id.ListView01);
list.setAdapter(adapter);
}
the error area is highlighted
Thank you

Related

[DEV] - How to fix OutOfMemoryError

Hi, I'am developping an android app which use bitmap.
On my device (HTC Desire) it's work really fine, but in android dev console i have a lot of OutOfMemoryError, and after lot of try i can't resolve them.
Some codes of my apps :
Code:
public class ResizableBitmap
{
// bitmap large enough to be scrolled
private static Bitmap bmLargeImage;
// zoom leve
private float zoomLevel;
public ResizableBitmap( Context context, Bitmap drawable, float zoomLevel)
{
// load bitmap
bmLargeImage = drawable;
this.zoomLevel = zoomLevel;
// initialiastion par defaut
Display display = ( (WindowManager) context.getSystemService( Context.WINDOW_SERVICE ) ).getDefaultDisplay();
onSizeChanged( display.getWidth(), display.getHeight(), 0, 0 );
}
public void onSizeChanged( int w, int h, int oldw, int oldh )
{
... some code
// redimensionnement
bmLargeImage = resize( bmLargeImage, w );
... some code
}
private Bitmap resize( Bitmap bm, int w )
{
// initial size
int width = bm.getWidth();
int height = bm.getHeight();
// zoom level (zoom is always up to 1)
w *= zoomLevel;
// scale
float scaleWidth = ( (float) w ) / width;
float scaleHeight = ( (float) w ) / width;
Matrix matrix = new Matrix();
matrix.postScale( scaleWidth, scaleHeight );
Bitmap resizedBitmap = Bitmap.createBitmap( bm, 0, 0, width, height, matrix, true );
return resizedBitmap;
}
}
And with this i have some errors like that (sometime on instantiation or during real onSizeChanged event)
Code:
java.lang.OutOfMemoryError
at android.graphics.Bitmap.nativeCreate(Native Method)
at android.graphics.Bitmap.createBitmap(Bitmap.java:604)
at android.graphics.Bitmap.createBitmap(Bitmap.java:540)
at com.vinc.testapps.commons.view.ResizableBitmap.resize(ResizableBitmap.java:107)
at com.vinc.testapps.commons.view.ResizableBitmap.onSizeChanged(ResizableBitmap.java:71)
If someone can help me to explain what is wrong.
Thanks a lot
read about first "decode" and then "recycle" bitmap after usage, this will help.
You will find tons of threads..
greets
Yo just reboot into recovery n whipe cache... Had the same problem with my evo3D
Hope that helps!
Sent from my PG86100 using xda premium
Reading the code gives no clue as to why the bmLargeImage is declared as static.
Seeing as the ResizableBitmap has a constructor and an instance of it is used to manipulate the image, I can see no reason to why this private member should be declares as static ..
(as bmLargeImage is private, it can only be accessed from within an instance of ResizableBitmap, or from classes within the same .java file if you have any, but declaring it as static tells that it could be accessed without having an actual instance of ResizableBitmap)
Perhaps the error will dissapear if you simply remove the static declaration, or perhaps you'll need to clean up and nulling the bitmap references a bit.
Not sure if this helped, or if there are more to this code than is posted here but judging from the posted code I would suggest reading up on some google results android memory leaks, bitmaps and static fields.
Good luck
Questions or Problems Should Not Be Posted in the Development Forum
Please Post in the Correct Forums
Moving to Q&A

[HELP] Adding a Toast message to Decompress activity

Hi everyone,
I am currently working on my first app which grabs a ZIP from the internet and the extracts it to a certain location. Everything works great but I can not figure out how to show a Toast message when the extraction operation is done.
The code I am using for unzipping is:
Code:
package mmarin.test.download;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
*
* @author jon
*/
public class Decompress{
private String _zipFile;
private String _location;
byte[] buffer = new byte[1024];
int length;
public Decompress(String zipFile, String location) {
_zipFile = zipFile;
_location = location;
_dirChecker("");
}
public void unzip() {
try {
FileInputStream fin = new FileInputStream(_zipFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
Log.v("Decompress", "Unzipping " + ze.getName());
if(ze.isDirectory()) {
_dirChecker(ze.getName());
} else {
FileOutputStream fout = new FileOutputStream(_location + ze.getName());
while ((length = zin.read(buffer))>0) {
fout.write(buffer, 0, length);
}
zin.closeEntry();
fout.close();
}
}
zin.close();
} catch(Exception e) {
Log.e("Decompress", "unzip", e);
}
}
private void _dirChecker(String dir) {
File f = new File(_location + dir);
if(!f.isDirectory()) {
f.mkdirs();
}
}
}
I am calling the Decompress activity through a button:
Code:
Button decompress = (Button)findViewById(R.id.button1);
decompress.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
String zipFile = Environment.getExternalStorageDirectory() + "/IPM/Splash.zip";
String unzipLocation = Environment.getExternalStorageDirectory() + "/IPM/Splash/";
Decompress d = new Decompress(zipFile, unzipLocation);
d.unzip();
}
});
I found this here: http://www.jondev.net/articles/Unzipping_Files_with_Android_(Programmatically) and it works great.
As I said above, only issue is displaying a message that everything is done.
Can someone please help me out?
Thank you!
Please use the Q&A Forum for questions &
Read the Forum Rules Ref Posting
Moving to Q&A
Put the toast after zin.close()
www.stackoverflow.com
Here you can find what you want
Xperian using xda app
http://stackoverflow.com/questions/9824772/toast-after-email-intent-message
Check this
Xperian using xda app
RoberGalarga said:
Put the toast after zin.close()
Click to expand...
Click to collapse
Hey,
I tried this but it doesn't work. I used this statement:
Code:
Toast.makeText(this, "Extraction complete", "LENGTH_SHORT").show();
and I got this error message: The method makeText(Context, CharSequence, int) in the type Toast is not applicable for the arguments (Decompress, String, String).
Help?
The method makeText(Context, CharSequence, int) in the type Toast is not applicable for the arguments (Decompress, String, String)
What the above line means is that you need to pass a Context object, a CharSequence object and an int. You are passing the wrong object types (Decompress, String, String).
The example you saw used the Toast in the activity class itself, that is why the first value passed was a this. The "LENGTH_SHORT" is actually a constant Toast.LENGTH_SHORT.
I am guessing you are making the button object in your main activity class. So i'd suggest making an additional method for the activity class that looks like this
Code:
public void displayToast(CharSequence cs)
{
Toast.makeText(this, cs, Toast.LENGTH_SHORT).show();
}
and then make the following change to your code
Code:
Button decompress = (Button)findViewById(R.id.button1);
decompress.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
String zipFile = Environment.getExternalStorageDirectory() + "/IPM/Splash.zip";
String unzipLocation = Environment.getExternalStorageDirectory() + "/IPM/Splash/";
Decompress d = new Decompress(zipFile, unzipLocation);
d.unzip();
// Add the following line
displayToast("Unzip complete");
}
});
Let me know if it worked for you.
The_R said:
The method makeText(Context, CharSequence, int) in the type Toast is not applicable for the arguments (Decompress, String, String)
What the above line means is that you need to pass a Context object, a CharSequence object and an int. You are passing the wrong object types (Decompress, String, String).
The example you saw used the Toast in the activity class itself, that is why the first value passed was a this. The "LENGTH_SHORT" is actually a constant Toast.LENGTH_SHORT.
I am guessing you are making the button object in your main activity class. So i'd suggest making an additional method for the activity class that looks like this
Code:
public void displayToast(CharSequence cs)
{
Toast.makeText(this, cs, Toast.LENGTH_SHORT).show();
}
and then make the following change to your code
Code:
Button decompress = (Button)findViewById(R.id.button1);
decompress.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
String zipFile = Environment.getExternalStorageDirectory() + "/IPM/Splash.zip";
String unzipLocation = Environment.getExternalStorageDirectory() + "/IPM/Splash/";
Decompress d = new Decompress(zipFile, unzipLocation);
d.unzip();
// Add the following line
displayToast("Unzip complete");
}
});
Let me know if it worked for you.
Click to expand...
Click to collapse
PERFECT! You're amazing!

[Q] can't transform xml+xsl(with exslt) to html

Hi guys, I am developing an app which loads a xml and a xsl and loads the resulting html, displaying it on the screen. It works perfectly when the xsl does not have exslt functions. However, when it does contain exslt functions, it doesn't work.
The code is rather small, so I'm posting it here:
Code:
public class MainActivity extends Activity {
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView webview = new WebView(this);
setContentView(webview);
Source xmlSource = new StreamSource(this.getResources().openRawResource(R.raw.xml2));
Source xsltSource = new StreamSource(this.getResources().openRawResource(R.raw.xsl2));
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = null;
ByteArrayOutputStream output = null;
StreamResult result;
try
{
transformer = tFactory.newTransformer(xsltSource);
output = new ByteArrayOutputStream();
result = new StreamResult(output);
transformer.transform(xmlSource, result);
} catch (TransformerException e)
{
e.printStackTrace();
}
ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
String html = new Scanner(input,"UTF-8").useDelimiter("\\A").next();
webview.loadData(html, "text/html", "UTF-8");
}
[user=439709]@override[/user]
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;
}
}
I have attached a zip file containing 5 files: xml,xsl, xml2,xsl2, logcat.
I get the errors with xml2 and xsl2.
I'm using the eclipse IDE, ADT bundle thing. In addition, I have tried an equivalent code in netbeans:
Code:
public class JavaApplication4 {
/**
* [user=955119]@param[/user] args the command line arguments
*/
public static void main(String[] args) throws TransformerConfigurationException, TransformerException, FileNotFoundException {
Source xmlSource = new StreamSource("xml2.xml");
Source xsltSource = new StreamSource("xsl2.xsl");
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer(xsltSource);
ByteArrayOutputStream output = new ByteArrayOutputStream();
StreamResult result = new StreamResult(output);
transformer.transform(xmlSource, result);
ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
String html = new Scanner(input,"UTF-8").useDelimiter("\\A").next();
System.out.println(html);
}
}
which, to my surprise, works for both xml and xsl.
Please help me, I've been trying to make it work for hours...I've tried many stuff, different codes...but it doesn't seem to have anything to do with my code.
Thank you for your time.

How to add Admob in Custom Dialog?

Hi guys!
I'm trying to implement Admob banner in Custom Dialog box.
I want to make in in XML 'cause i'm thinking this is simplier to change it positions etc.
So here is fragment from my GameActivity where is Custom Dialog too.
Fragment with dialog:
Code:
public void showRestartDialog() {
final Dialog dialog = new Dialog(GameActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.setContentView(R.layout.activity_dialog);
//set up image view
ImageView img = (ImageView) dialog.findViewById(R.id.imageView1);
img.setImageResource(R.drawable.puste);
int highest = PrefUtil.getHighestScore(this);
String text = null;
if (currentPoint > highest) {
highest = currentPoint;
PrefUtil.setHighestScore(this, currentPoint);
} else {
}
text = "\n " + currentPoint + "\n\n " + highest;
TextView text1 = (TextView)
dialog.findViewById(R.id.TextView01);
text1.setText(text);
[B] AdView adView = (AdView)dialog.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);[/B]
Where is a problem? With this code, the dialog is showing but without banner.
Help me please!
Greetings!
PS. If You need more code, please tell me.

Android Volley request weird “1 second” delay between multiple fast clicks

Sorry for my bad english, but i have problem and can't figure it out..
I have custom listview in my fragment for getting products from JSON array. And I have 3 ImageButtons in every listview row;
Plus Button(+), Minus Button(-) and Remove Button(X)..
So when i click each button, its calling JSON request for update product's piece number, getting new datas from response and repopulate array list.
Everything ok but, when I click that buttons faster, it seems there is 1 sec delay between multiple requests even first volley request has already done before.
Here is my JSON method in TableAdapter.java
Code:
[SIZE="3"]public void JSON(final int position, final int process) {
if (inProgress==false) {
dialog = new ProgressDialog(myContext);
dialog.setMessage("Updating.....");
dialog.show();
inProgress = true;
System.out.println("**** Now request is beginning............");
final int rowID = tableModelList.get(position).getID();
final int treeID = tableModelList.get(position).getAna_dal();
final float price = tableModelList.get(position).getBFiyat();
final int quantity = tableModelList.get(position).getAdet();
final int print = tableModelList.get(position).getYazdimi();
final String insertUrl = "This is URL for getting json array";
Map<String, String> parameters = new HashMap<>();
parameters.put("tableID", "" + getTableId);
parameters.put("rowID", "" + rowID);
parameters.put("treeID", ""+treeID);
parameters.put("process",""+process);
parameters.put("quantity",""+quantity);
parameters.put("price",""+price);
parameters.put("print",""+print);
CustomRequest jsObjRequest = new CustomRequest(Request.Method.POST, insertUrl, parameters, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray getOrders = response.getJSONArray("order");
Gson gson = new Gson();
tableModelList.clear();
for (int i = 0; i < getOrders.length(); i++) {
JSONObject order = getOrders.getJSONObject(i);
TableModel tableModel = gson.fromJson(order.toString(), TableModel.class);
tableModelList.add(tableModel);
}
mAdapter.notifyDataSetChanged();
System.out.println("**** onResponse: Request is done............");
System.out.println("**** JSON: "+response.toString());
dialog.cancel();
inProgress = false;
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError response) {
Log.d("Response: ", response.toString());
inProgress = false;
}
});
requestQueue.add(jsObjRequest);
}
}[/SIZE]
Dialog is showing when request beginning and canceling when request is done. But as I said, when I click faster, there is a delay between multiple requests even first request has already done. I'm saying 1 sec, because 2nd request is beginning after 1 sec exactly, no matter how I clicking fast. I can't figure it out..
I tested fast clicks to showing toasts with random numbers and it's working fine. But when I testing with JSON method, there is a weird delay.
I have SwipeRefreshLayout and ScrollView in my fragment. I'm using Volley with singleton.
Here is video to showing what my problem is;
Here is Logcat output for every click
Every fast click has returning success json output, but nothing change instantly on the screen..
Thanks for your help.

Categories

Resources