My app presents many images so I move from one image to the flowing one through a button (i10) and to go backward I used an other button (i8).
I think this method is a bit old fashion and I want to SWIPE between images, but I have really no clue, i read many about swiping but with no success.
here is my old fashion code:
num = 1;
imagename = getIntent().getExtras().getString("somekey");
resId = getApplicationContext().getResources().getIdentifier(
imagename + num, "drawable", getPackageName());
image1.setImageResource(resId);
num++;
i10.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
resId = getApplicationContext().getResources()
.getIdentifier(imagename + num, "drawable",
getPackageName());
} catch (NotFoundException e) {
e.printStackTrace();
}
if (resId > 0) {
image1.setImageResource(resId);
num++;
overridePendingTransition(R.anim.pushin, R.anim.pushout);
} else {
Intent i = new Intent(getApplicationContext(), Menu.class);
startActivity(i);
overridePendingTransition(R.anim.pushinhorizontal,
R.anim.pushouthorizontal);
}
}
});
i8.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
num = num - 2;
try {
resId = getApplicationContext().getResources()
.getIdentifier(imagename + num, "drawable",
getPackageName());
} catch (NotFoundException e) {
e.printStackTrace();
}
if (resId > 0) {
image1.setImageResource(resId);
num++;
overridePendingTransition(R.anim.pushin, R.anim.pushout);
} else {
Intent i = new Intent(getApplicationContext(), Menu.class);
startActivity(i);
overridePendingTransition(R.anim.pushinhorizontal,
R.anim.pushouthorizontal);
}
}
});
The best approach would be to use ViewPager
You can create a pager adapter and let the viewpager handles swipe operations.
Sample
Related
I'm newbie in android. After clicking this button(when nothing is in TextView i.e. it shows "" ) I'm getting NumberFormatException but in other cases it is working .I want to show toast message if nothing is in the String and my TextView initially is
android:id="#+id/text_view_result"
android:text=""
that button is
buttonExpense.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Integer.valueOf(result) < 0) {
Toast.makeText(getActivity().getApplicationContext(), "Amount can't be negative", Toast.LENGTH_SHORT).show();
return;
}
else if (Integer.valueOf(result) > 0) {
Intent intent = new Intent(fa2, EditorActivity.class);
intent.putExtra("result", result);
startActivity(intent);
}
else if(Integer.valueOf(result) == 0) {
Toast.makeText(getActivity().getApplicationContext(), "Amount can't be 0", Toast.LENGTH_SHORT).show();
return;
}
else{
Toast.makeText(getActivity().getApplicationContext(), "Please enter your amount", Toast.LENGTH_SHORT).show();
return;
}
}
});
method where result String is used is in method as given below
private void onEqualButtonClicked() {
int res = 0;
try {
int number = Integer.valueOf(tmp);
int number2 = Integer.valueOf(resultTextView.getText().toString());
switch (operator) {
case "+":
res = number + number2;
break;
case "/":
res = number / number2;
break;
case "-":
res = number - number2;
break;
case "X":
res = number * number2;
break;
}
result = String.valueOf(res);
resultTextView.setText(result);
}
catch (Exception e) {
e.printStackTrace();
}
An empty string is not a number. What you want to do is check if it's a number first and then handle it.
int number;
try {
number = Integer.parseInt(result);
} catch (NumberFormatException exception) {
// handle case where it's not a number
}
// perform logic where it is a number
I'm trying to pass captured image and valuefrom C to B, finally to listView A. When the list in Activity A is clicked, it will display the passed image on imageView and values on editText B . But the problem now is the image displayed on Activity B is not from row I have clicked on listview A.
Activity A
ArrayAdapter<String> adapter;
ArrayList<String> m_listItems = new ArrayList<String>();
int mClickedPosition;
adapter=new ArrayAdapter<String (getActivity(),R.layout.claims,R.id.textView1,m_listItems);
listV = (ListView) claims.findViewById(R.id.listView1);
listV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> listView, View view,int position, long id)
{
mClickedPosition = position;
String temp[] = m_listItems.get(position).split("\\s\\s+");
result = temp[temp.length - 1].trim();
result = result.replace("RM", "");
name = temp[1].trim();
Log.e("TAG", result + "");
if (name.equals("Project"))
{
Intent intent = new Intent(Claims1.this.getActivity(), Project1.class);
intent.putExtra("bitmap", true);
intent.putExtra("name", name);
intent.putExtra("result", result);
startActivityForResult(intent, 0);
Log.e("RESULT", "Result= " + result);
}
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 0: // for Project
result = data.getStringExtra("text"); //get from B
name = data.getStringExtra("a");
description = data.getStringExtra("c");
Log.d("FIRST", "result:" + result);
Text = " " + name + " " + "RM" + result + "";
if (mClickedPosition == -1)
{ // if is icon button clicked
m_listItems.add(Text);
}
else
{
m_listItems.set(mClickedPosition, Text);
}
adapter.notifyDataSetChanged();
listV.setAdapter(adapter);
break;
}
}
Activity B
if(getIntent().getExtras()!=null) { //if has value pass from A
final String Amount = getIntent().getExtras().getString("result");
final String description1 = getIntent().getExtras().getString("description");
txt1.setText(description1);
txt.setText(Amount);
}
b.setOnClickListener(new View.OnClickListener() { // return to A
public void onClick(View arg0) {
Intent returnIntent = new Intent();
a = "Project";
text = txt.getText().toString(); // amount
returnIntent.putExtra("text", text);
returnIntent.putExtra("a", a);
returnIntent.putExtra("c", c); // receive from Activity C
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
viewImage.setImageBitmap(Global.img); // image receive from C
}
public void onActivityResult(int requestCode,int resultCode, Intent data)
{ //receive from C
if(requestCode==PROJECT_REQUEST_CODE) {
if(data!=null&&data.hasExtra("text")) {
c = data.getStringExtra("text");
txt1.setText(c);
viewImage.setImageBitmap(Global.img); //display image
}
}
else if (requestCode==CAMERA_REQUEST_CODE)
{
}
}
Activity C
ImageView b;
ok.setOnClickListener(new View.OnClickListener()
{ // return image to B
public void onClick(View arg0)
{
Intent returnIntent=new Intent();
text=t.getText().toString();
b.setDrawingCacheEnabled(true);
b.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
b.layout(0, 0, b.getMeasuredWidth(), b.getMeasuredHeight());
b.buildDrawingCache(true);
returnIntent.putExtra("text", text);
if (b.getDrawingCache() != null) {
Bitmap bitmap = Bitmap.createBitmap(b.getDrawingCache());
if (bitmap == null) {
Log.e("TAG", "getDrawingCache() == null");
}
Global.img = bitmap;
}
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
}
Add image into database
When ok button in Activity A is clicked, I want save all the image todatabase.
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
byte[] data=getBitmapAsByteArray(getActivity(),Global.img);// this is a function
SB.insertStaffBenefit(data);
}
}
}
public static byte[] getBitmapAsByteArray(final Context context,Bitmap bitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, outputStream);
Toast.makeText(context, outputStream.size()/1024+"KB", Toast.LENGTH_LONG).show();
return outputStream.toByteArray();
}
1: ListView in A. Values were get fom C and B.
2: Activity B. Assume the list is clicked and intent to B. Noted that the value and image are from Activity C and B.
3: New value and images added and return to A
4: Two list in Activity A now
5: When first list clicked, image changed
You may add bitmap array list (in your Activity A):
ArrayList<Bitmap> m_listBitmapItems = new ArrayList<Bitmap>();
in onItemClick of your listV:
Global.img = m_listBitmapItems.get(position);
in onActivityResult():
if (mClickedPosition == -1)
{ // if is icon button clicked
m_listItems.add(Text);
m_listBitmapItems.add(Global.img);
}
else
{
m_listItems.set(mClickedPosition, Text);
m_listBitmapItems.set(mClickedPosition, Global.img);
}
I'm making an quiz app in which there are two buttons i.e next and previous for fetching next and prev question. I'm able to fetch the next question but didn't able to fetch previous question. Done lots of google and R&D regarding this but didn't get any right solution.
Here is my code:
Database:
public List<NotificationListItem> getNQuestions(String tid) {
List<NotificationListItem> quest = new ArrayList<NotificationListItem>();
openToRead();
Cursor cursor = db.rawQuery("SELECT * FROM quiz_list"+ " where tid = ?", new String[] { tid});
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
NotificationListItem item = new NotificationListItem();
int id=cursor.getColumnIndex(QuizTable.KEY_QID);
int answer=cursor.getColumnIndex(QuizTable.KEY_ANSWER);
int testid=cursor.getColumnIndex(QuizTable.KEY_TESTID);
int questions=cursor.getColumnIndex(QuizTable.KEY_QUES);
int option1=cursor.getColumnIndex(QuizTable.KEY_OP1);
int option2=cursor.getColumnIndex(QuizTable.KEY_OP2);
int option3=cursor.getColumnIndex(QuizTable.KEY_OP3);
int option4=cursor.getColumnIndex(QuizTable.KEY_OP4);
int option5=cursor.getColumnIndex(QuizTable.KEY_OP5);
int anscount=cursor.getColumnIndex(QuizTable.KEY_ANSC);
int totalchoice=cursor.getColumnIndex(QuizTable.KEY_TC);
item.qID=cursor.getInt(id);
item.answer=cursor.getString(answer);
item.testID=cursor.getString(testid);
item.questions=cursor.getString(questions);
item.option1=cursor.getString(option1);
item.option2=cursor.getString(option2);
item.option3=cursor.getString(option3);
item.option4=cursor.getString(option4);
item.option5=cursor.getString(option5);
item.anscount=cursor.getString(anscount);
item.tc=cursor.getString(totalchoice);
quest.add(item);
} while (cursor.moveToNext());
}
// return quest list
return quest;
}
QuizActivity:
NotificationListItem Nitem;
List<NotificationListItem> Nquest;
nextBT = (Button) findViewById(R.id.nextBtIV);
prevBT = (Button) findViewById(R.id.prevIV);
prevBT.setEnabled(false);
quizTable = new QuizTable(this);
quizTable.openToRead();
quizTable.openToWrite();
Nquest=quizTable.getNQuestions(testID);
Nitem=Nquest.get(questionid);
setQuestionView();
nextBT.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
resultquiz();
if(qID<Nquest.size()){
Nitem=Nquest.get(qID);
prevBT.setEnabled(true);
setQuestionView();
qID++;
}
else{
Intent intent = new Intent(QuizActivityB.this, TestAnalysisActivity.class);
intent.putExtra("totalquestion",qs);
intent.putExtra("testtime",time);
intent.putExtra("testname", testName);
intent.putExtra("testID", testID);
intent.putExtra("currentDateandTime", date);
intent.putExtra("totalattemp",totalattempt);
intent.putExtra("totalMarks", totalMarks);
intent.putExtra("subject", subject);
intent.putExtra("score", finalscore);
intent.putExtra("percentage", percentage);
intent.putExtra("timecounter", timeCounterFinish);
intent.putExtra("correctAns", cAns);
intent.putExtra("negativeAns", nAns);
intent.putExtra("comments", comments);
startActivity(intent);
finish();
}}
});
prevBT.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(qID>0){
Pitem=Pquest.get(qID);
setQuestionView();
qID--;
}}
});
private void setQuestionView()
{
txtQuestion.setText(Nitem.getquestions());
op1=(Nitem.getOption1());
op2=(Nitem.getOption2());
op3=(Nitem.getOption3());
op4=(Nitem.getOption4());
op5=(Nitem.getOption5());
ans=(Nitem.getAnswer());
ansc=Nitem.getAnscount();
tc=(Nitem.getTc());
questionid=(Nitem.getqID());
totalchoice=Integer.parseInt(tc);
anscount=Integer.parseInt(ansc);
System.out.println("QUESTIONID="+questionid);
System.out.println("ANSWER="+ans);
if(anscount==1)
{
rc.removeAllViews();
addRadioButtons();
}
else if(anscount>1)
{
rc.removeAllViews();
addCheckButtons();
}
}
You could create youself an int variable which you should increment or decrement, and fetch desired record from ArrayList using list.get(variable).
ive stored some image names in a sqlite database.My code is supposed to retrieve all the imagenames and store it in a array and then assign the first image to an imageview based on its name.Im using UIL to set the images to the image view.
MY CODE
public class Locker extends Activity {
int index = 0, limit, tolerance = 40, state = 1;
String[] bgimg;
String[] ranimg;
int[] ActXCod;
int[] ActYCod;
ImageView image;
ImageLoader imageloader;
File Path;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.locker);
image = (ImageView) findViewById(R.id.imageView1);
SharedPreferences getprefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
String temp = getprefs.getString("ImageSeqNo", "4");
limit = Integer.parseInt(temp);
Path = getExternalFilesDir(null);
Constants cons = new Constants();
ranimg = cons.getImagePath(Path.toString());
imageloader = ImageLoader.getInstance();
try {
new Thread(new getData()).start();
imageloader.displayImage("file://" + Path.toString() + "/"
+ bgimg[index], image);
} catch (Exception e) {
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("ERROR");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
}
}
public boolean onTouchEvent(MotionEvent event) {
// MotionEvent object holds X-Y values
if (event.getAction() == MotionEvent.ACTION_DOWN) {
int XCood = (int) event.getX();
int YCood = (int) event.getY();
int XMin = ActXCod[index] - tolerance, XMax = ActXCod[index]
+ tolerance, YMin = ActYCod[index] - tolerance, YMax = ActYCod[index]
+ tolerance;
/*
* String text = "You clicked at x = " + XCood + " and y = " +
* YCood; final Toast toast = Toast.makeText(this, text,
* Toast.LENGTH_SHORT); toast.show(); Handler handler = new
* Handler(); handler.postDelayed(new Runnable() {
*
* #Override public void run() { toast.cancel(); } }, 750);
*/
if (index < (limit - 1)) // loop to check number of images
{
// loop to check status
if ((state == 1)
&& (((XCood > XMin) && (XCood < XMax)) && ((YCood > YMin) && (YCood < YMax)))) {
index++;
imageloader.displayImage("file://" + Path.toString() + "/"
+ bgimg[index], image);
} else {
index++;
Random r = new Random();
int ran = r.nextInt(10 - 0);
imageloader.displayImage("file://" + ranimg[ran], image);
state = 0;
}
} else {
if (state == 1) {
Intent i = new Intent(Locker.this, Compare_Pattern.class);
startActivity(i);
finish();
} else {
new AlertDialog.Builder(this)
.setTitle("Failed Login Attempt")
.setMessage(
"Your previous login attempt has failed.Would you like to try again?")
.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
// continue with delete
Intent intent = getIntent();
startActivity(intent);
finish();
}
})
.setNegativeButton(android.R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
// do nothing
finish();
}
}).show();
}
}
}
return super.onTouchEvent(event);
}
#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;
}
class getData implements Runnable {
#Override
public void run() {
// TODO Auto-generated method stub
DataBaseHandler handler = new DataBaseHandler(
getApplicationContext());
handler.open();
ActXCod = handler.getXcod();
ActYCod = handler.getYcod();
bgimg = handler.getImg();
handler.close();
}
}
}
i tried debugging the code and its giving me a Java.lang.NullPointerException for bgimg[index] at the line imageloader.displayImage("file://" + Path.toString() + "/" + bgimg[index], image);. i cannot figure out why. Any help is gratefully accepted.
new Thread(new getData()).start();
imageloader.displayImage("file://" + Path.toString() + "/"
+ bgimg[index], image);
bgimg is not initialized yet. Even if you start your thread, it does not run and compelete initialization of bgimg immediately.
Move the code that requires the result of the thread code into the thread itself. You can use Activity.runOnUiThread() to move the execution back to UI thread from a background thread.
I'm having trouble with making my randomly generated image, which is interpreted as a button, become clickable. Each leads to a different activity.
The random images work perfect actually, the only problem it's not clickable.
Here's my Main.java:
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);
final List<String> images = new ArrayList<String>();
for (int i=1; i<=13; i++) {
images.add("img"+i);
}
final Button imgView = (Button)findViewById(R.id.top1);
String imgName = null;
int id = 0;
Collections.shuffle(images, new Random());
imgName = images.remove(0);
imageRandomizer(imgName, id, imgView);
}
public void imageRandomizer(String imgName, int id, final Button imgView) {
id = getResources().getIdentifier(imgName,
"drawable",
getPackageName());
imgView.setBackgroundResource(id);
}
}
On my layout, I specified the id top1 as a Button. So the above code will look up to my drawable images, which have the names img1.jpg, img2.jpg, img3.jpg , until img13.jpg.
Making an ImageButton clickable to one activity without being dependent on the shown random image is easy, I can do it without problem.
But what I wanna make is something like, when img1.jpg is generated, it becomes clickable and leads to Activity1.java, for img2.jpg the intent goes to Activity2.java, etc.
EDIT
#Roflcoptr
Here's my OnClickListener:
private OnClickListener top_listener = new OnClickListener() {
public void onClick(View v) {
switch((Integer) v.getTag()) {
case 1:
Intent aid = new Intent(Main.this, ProjektAID.class);
startActivity(aid);
case 2:
Intent adh = new Intent(Main.this, ProjektADH.class);
startActivity(adh);
case 3:
Intent bos = new Intent(Main.this, ProjektBOS.class);
startActivity(bos);
case 4:
Intent brot = new Intent(Main.this, ProjektBROT.class);
startActivity(brot);
case 5:
Intent care = new Intent(Main.this, ProjektCARE.class);
startActivity(care);
case 6:
Intent caritas = new Intent(Main.this, ProjektCARITAS.class);
startActivity(caritas);
case 7:
Intent doc = new Intent(Main.this, ProjektDOC.class);
startActivity(doc);
case 8:
Intent drk = new Intent(Main.this, ProjektDRK.class);
startActivity(drk);
case 9:
Intent give = new Intent(Main.this, ProjektGIVE.class);
startActivity(give);
case 10:
Intent hive = new Intent(Main.this, ProjektHIV.class);
startActivity(hive);
case 11:
Intent jo = new Intent(Main.this, ProjektJOHANNITER.class);
startActivity(jo);
case 12:
Intent kind = new Intent(Main.this, ProjektKINDERHERZ.class);
startActivity(kind);
case 13:
Intent kult = new Intent(Main.this, ProjektKULTURGUT.class);
startActivity(kult);
}
}
};
and here's the randomizer method:
public void imageRandomizer(String imgName, int id, final Button imgView) {
id = getResources().getIdentifier(imgName, "drawable", getPackageName());
imgView.setBackgroundResource(id);
imgView.setTag(new Integer(1)); //example for image 1
if (imgName.equals("img1")) {
imgView.setTag(new Integer(1)); //example for image 1
} else if (imgName.equals("img2")) {
imgView.setTag(new Integer(2));
} else if (imgName.equals("img3")) {
imgView.setTag(new Integer(3));
} else if (imgName.equals("img4")) {
imgView.setTag(new Integer(4));
} else if (imgName.equals("img5")) {
imgView.setTag(new Integer(5));
} else if (imgName.equals("img6")) {
imgView.setTag(new Integer(6));
} else if (imgName.equals("img7")) {
imgView.setTag(new Integer(7));
} else if (imgName.equals("img8")) {
imgView.setTag(new Integer(8));
} else if (imgName.equals("img9")) {
imgView.setTag(new Integer(9));
} else if (imgName.equals("img10")) {
imgView.setTag(new Integer(10));
} else if (imgName.equals("img11")) {
imgView.setTag(new Integer(11));
} else if (imgName.equals("img12")) {
imgView.setTag(new Integer(12));
}
else if (imgName.equals("img13")) {
imgView.setTag(new Integer(13));
}
}
I would use a tag to identify the button. So in your imateRandomizer add a unique ID for each possible Image. I don't know how you can identify the images uniquely, but I'll show the example here for the name:
public void imageRandomizer(String imgName, int id, final Button imgView)
{
id = getResources().getIdentifier(imgName, "drawable", getPackageName());
imgView.setBackgroundResource(id);
if (imgName.equals("Name of the Image for your first activity") {
imgView.setTag(new Integer(1)); //example for image 1
} else if (imgName.equals("Name of the Image for your second activity") {
imgView.setTag(new Integer(2));
}
}
And then In your ClickListener you can check which tag the button has:
imgView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
switch((Integer) v.getTag()) {
case 1: //start Activity 1;
break;
case 2: //start Activity 2;
break;
}
}
});