I am working on a side project in android studio and need to store some long term data to a file that can be written and readable, I am able to do this outside of android studio, but when I try to do it within, it sows a error saying
public void onClick(View v) 'onClick(View)' in 'Anonymous class derived from android.view.View.OnClickListener' clashes with 'onClick(View)' in 'android.view.View.OnClickListener'; overridden method does not throw 'java.io.FileNotFoundException'{
I have a function in a separate file that writes to a string from a file, but when I try to access that string from one of my main view pages, its asking for an exception, but will not work with said exception, I've tried try and catch but with no success
File being initialized and written:
package com.example.stellarisspeciesrandomizer;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import androidx.appcompat.app.AppCompatActivity;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
public class DLCPage extends AppCompatActivity {
public static int[] DLCArray;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().hide();
setContentView(R.layout.dlc_page);
try {
File myObj = new File("hasDLC.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
DLCArray = new int[1];
Button doneButton = (Button) findViewById(R.id.button_done);
doneButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) throws IOException {
writeToFile();
finish();
}});
ImageButton aquaticsCheckbox = (ImageButton) findViewById(R.id.aquatic_checkbox);
aquaticsCheckbox.setTag("1");
//hello
aquaticsCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (aquaticsCheckbox.getTag() == "1") {
aquaticsCheckbox.setImageResource(R.drawable.checked);
aquaticsCheckbox.setTag("2");
DLCArray[0] = 1;
} else if (aquaticsCheckbox.getTag() == "2") {
aquaticsCheckbox.setImageResource(R.drawable.checkmark);
aquaticsCheckbox.setTag("1");
DLCArray[0] = 0;
}
}
});
ImageButton humanoidCheckbox = (ImageButton) findViewById(R.id.humanoid_checkbox);
humanoidCheckbox.setTag("1");
humanoidCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (humanoidCheckbox.getTag() == "1") {
humanoidCheckbox.setImageResource(R.drawable.checked);
humanoidCheckbox.setTag("2");
DLCArray[1] = 1;
} else if (humanoidCheckbox.getTag() == "2") {
humanoidCheckbox.setImageResource(R.drawable.checkmark);
humanoidCheckbox.setTag("1");
DLCArray[1] = 0;
}
}
});
ImageButton plantoidCheckbox = (ImageButton) findViewById(R.id.plantoid_checkbox);
plantoidCheckbox.setTag("1");
plantoidCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (plantoidCheckbox.getTag() == "1") {
plantoidCheckbox.setImageResource(R.drawable.checked);
plantoidCheckbox.setTag("2");
DLCArray[2] = 1;
} else if (plantoidCheckbox.getTag() == "2") {
plantoidCheckbox.setImageResource(R.drawable.checkmark);
plantoidCheckbox.setTag("1");
DLCArray[2] = 0;
}
}
});
ImageButton syntheticCheckbox = (ImageButton) findViewById(R.id.synthetic_checkbox);
syntheticCheckbox.setTag("1");
syntheticCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (syntheticCheckbox.getTag() == "1") {
syntheticCheckbox.setImageResource(R.drawable.checked);
syntheticCheckbox.setTag("2");
DLCArray[3] = 1;
} else if (syntheticCheckbox.getTag() == "2") {
syntheticCheckbox.setImageResource(R.drawable.checkmark);
syntheticCheckbox.setTag("1");
DLCArray[3] = 0;
}
}
});
ImageButton necroidCheckbox = (ImageButton) findViewById(R.id.necroids_checkbox);
necroidCheckbox.setTag("1");
necroidCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (necroidCheckbox.getTag() == "1") {
necroidCheckbox.setImageResource(R.drawable.checked);
necroidCheckbox.setTag("2");
DLCArray[4] = 1;
} else if (necroidCheckbox.getTag() == "2") {
necroidCheckbox.setImageResource(R.drawable.checkmark);
necroidCheckbox.setTag("1");
DLCArray[4] = 0;
}
}
});
ImageButton lithoidCheckbox = (ImageButton) findViewById(R.id.lithoids_checkbox);
lithoidCheckbox.setTag("1");
lithoidCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (lithoidCheckbox.getTag() == "1") {
lithoidCheckbox.setImageResource(R.drawable.checked);
lithoidCheckbox.setTag("2");
DLCArray[5] = 1;
} else if (lithoidCheckbox.getTag() == "2") {
lithoidCheckbox.setImageResource(R.drawable.checkmark);
lithoidCheckbox.setTag("1");
DLCArray[5] = 0;
}
}
});
ImageButton ancientCheckbox = (ImageButton) findViewById(R.id.ancient_checkbox);
ancientCheckbox.setTag("1");
ancientCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (ancientCheckbox.getTag() == "1") {
ancientCheckbox.setImageResource(R.drawable.checked);
ancientCheckbox.setTag("2");
DLCArray[6] = 1;
} else if (ancientCheckbox.getTag() == "2") {
ancientCheckbox.setImageResource(R.drawable.checkmark);
ancientCheckbox.setTag("1");
DLCArray[6] = 0;
}
}
});
ImageButton federationsCheckbox = (ImageButton) findViewById(R.id.federations_checkbox);
federationsCheckbox.setTag("1");
federationsCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (federationsCheckbox.getTag() == "1") {
federationsCheckbox.setImageResource(R.drawable.checked);
federationsCheckbox.setTag("2");
DLCArray[7] = 1;
} else if (federationsCheckbox.getTag() == "2") {
federationsCheckbox.setImageResource(R.drawable.checkmark);
federationsCheckbox.setTag("1");
DLCArray[7] = 0;
}
}
});
ImageButton apocalypseCheckbox = (ImageButton) findViewById(R.id.apocalypse_checkbox);
apocalypseCheckbox.setTag("1");
apocalypseCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (apocalypseCheckbox.getTag() == "1") {
apocalypseCheckbox.setImageResource(R.drawable.checked);
apocalypseCheckbox.setTag("2");
DLCArray[8] = 1;
} else if (apocalypseCheckbox.getTag() == "2") {
apocalypseCheckbox.setImageResource(R.drawable.checkmark);
apocalypseCheckbox.setTag("1");
DLCArray[8] = 0;
}
}
});
ImageButton utopiaCheckbox = (ImageButton) findViewById(R.id.utopia_checkbox);
utopiaCheckbox.setTag("1");
utopiaCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (utopiaCheckbox.getTag() == "1") {
utopiaCheckbox.setImageResource(R.drawable.checked);
utopiaCheckbox.setTag("2");
DLCArray[9] = 1;
} else if (utopiaCheckbox.getTag() == "2") {
utopiaCheckbox.setImageResource(R.drawable.checkmark);
utopiaCheckbox.setTag("1");
DLCArray[9] = 0;
}
}
});
}
public static void writeToFile() throws IOException {
int len = DLCArray.length;
for (int i = 0; i < len; i++) {
FileWriter writer = new FileWriter("hasDLC.txt");
writer.write(DLCArray[i] + "\t"+ "");
}
}
}
second page
package com.example.stellarisspeciesrandomizer;
import android.view.View;
import android.widget.ImageView;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class Randomizer {
private static int[] tall= new int[3] ;
public static String RandomSpecies(String origin) throws FileNotFoundException {
readFile();
Random random = new Random();
ArrayList<String> originArray = new ArrayList<String>();
String origins1 = "Prosperous Unification";
String origins2 = "Galactic Doorstep";
String origins3 = "Lost Colony";
String origins4 = "Here Be Dragons";
String origins5 = "Ocean Paradise";
String origins6 = "Clone Army";
String origins7 = "Necrophage";
String origins18 = "Resource Consolidation";
String origins19 = "Remnants";
String origins16 = "Life Seeded";
String origins17 = "Post-Apocalyptic";
String origins8 = "Remnants";
String origins9 = "Shattered Ring";
String origins10 = "Void Dwellers";
String origins11 = "Scion";
String origins12 = "On The Shoulders of Giants";
String origins13 = "Common Ground";
String origins14 = "Hegemon";
String origins15 = "Doomsday";
String origin20 = "Syncretic Evolution";
String origin21 = "Mechanist";
String origin22 = "String of Life";
originArray.add(origins4);
originArray.add(origins5);
originArray.add(origins6);
originArray.add(origins7);
originArray.add(origins18);
originArray.add(origins19);
originArray.remove(origins17);
originArray.remove(origins16);
originArray.add(origins8);
originArray.add(origins9);
originArray.add(origins10);
originArray.add(origins11);
originArray.add(origins12);
originArray.add(origins13);
originArray.add(origins14);
originArray.add(origins15);
originArray.add(origin20);
originArray.add(origin21);
originArray.add(origin22);
originArray.add(origins1);
originArray.add(origins2);
originArray.add(origins3);
origin = originArray.get(random.nextInt(originArray.size()));
return origin;
}
public static void readFile() throws FileNotFoundException {
Scanner scanner = new Scanner(new File("hasDLC.txt"));
tall = new int [100];
int i = 0;
while(scanner.hasNextInt()){
tall[i++] = scanner.nextInt();
}
System.out.println(tall);
}
}
last page
package com.example.stellarisspeciesrandomizer;
import static com.example.stellarisspeciesrandomizer.Randomizer.RandomSpecies;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;
import java.io.FileNotFoundException;
public class RandomizerHome extends AppCompatActivity {
String hi = "hi";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().hide();
setContentView(R.layout.randomizer_layout);
ImageView originImageView =(ImageView) findViewById(R.id.originImageView);
Intent dlcIntent = new Intent(this, DLCPage.class);
Button dlcButton = (Button) findViewById(R.id.dlc_button);
dlcButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(dlcIntent);
}
});
Button randomizeButton = (Button) findViewById(R.id.randomize_button);
randomizeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) throws FileNotFoundException {
String originTrue = "hi";
originTrue = RandomSpecies(hi);
switch(originTrue){
case ("Prosperous Unification"): originImageView.setImageResource(R.drawable.prosperousunification);break;
case ("Galactic Doorstep"): originImageView.setImageResource(R.drawable.galacticdoorstep);break;
case ("Lost Colony"): originImageView.setImageResource(R.drawable.lostcolony);break;
case ("Here Be Dragons"): originImageView.setImageResource(R.drawable.here_be_dragons);break;
case ("Ocean Paradise"): originImageView.setImageResource(R.drawable.ocean_paradise);break;
case ("Clone Army"): originImageView.setImageResource(R.drawable.clones);break;
case ("Necrophage"): originImageView.setImageResource(R.drawable.necrophage);break;
case ("Resource Consolidation"): originImageView.setImageResource(R.drawable.resource_consolidation);break;
case ("Remnants"): originImageView.setImageResource(R.drawable.remnant);break;
case ("Life Seeded"): originImageView.setImageResource(R.drawable.life_seeded);break;
case ("Post-Apocalyptic"): originImageView.setImageResource(R.drawable.post_apocalyptic);break;
case ("Shattered Ring"): originImageView.setImageResource(R.drawable.shattered_ring);break;
case ("Void Dwellers"): originImageView.setImageResource(R.drawable.void_dwellers);break;
case ("Scion"): originImageView.setImageResource(R.drawable.scion);break;
case ("On The Shoulders of Giants"): originImageView.setImageResource(R.drawable.on_the_shoulders_of_giant);break;
case ("Common Ground"): originImageView.setImageResource(R.drawable.common_ground);break;
case ("Hegemon"): originImageView.setImageResource(R.drawable.hegemon);break;
case ("Doomsday"): originImageView.setImageResource(R.drawable.doomsday);break;
case ("Syncretic Evolution"): originImageView.setImageResource(R.drawable.syncretic_evolution);break;
case ("Mechanist"): originImageView.setImageResource(R.drawable.mechanist);break;
case ("Tree of Life"): originImageView.setImageResource(R.drawable.tree_of_life);break;
}
System.out.println(originTrue);
}
});
}
}
Here:
randomizeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) throws FileNotFoundException {
What you are doing here: define an anonymous subclass of View.OnClickListener. And when you check the documentation for that class, it says:
public abstract void onClick (View v)
Now read the compiler message again you got. overridden method does not throw 'java.io.FileNotFoundException'
Thus the real answer here is: A) you have to understand what you are doing and B) you have to read compiler error messages really carefully.
Long story short, you can not override an inherited method and add checked exceptions such as FileNotFoundException to the signature of your method. So, the solution is to step back and to really learn/understand how exception handling works in Java. One possibility here: use try/catch in your readFile(), catch the FileNotFoundException and rethrow it as (unchecked) RuntimeException. Then you do not need to have throws FileNotFoundException on your method signatures, and the compiler won't complain any more.
Related
I have one recycle list view .In this I have one button .on click list view item button shows.On button click I hit one api to perform action .After performing action ,at the bottom of list automatically one item get repeat. when ever I perform api hit action same time items add at the bottom of list .Like as I perform api hit action 4 times then every time one-one item get add at the bottom of list . Please provide me solution to resolve this.
Below I'm providing code of my adapter class :-
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.VolleyError;
import com.dockedinDoctor.app.R;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pojo.AvailableTimeSlots;
import pojo.GetBlockedTimings;
import pojo.GetDoctorScheduleDetail;
import utils.Common;
import utils.ItemClickListener;
import utils.NetworkManager;
import utils.NetworkResponseListenerJSONObject;
import utils.SessionManager;
import utils.ShowMessage;
import static utils.Common.createProgressDialog;
public class MyScheduleAdapter extends RecyclerView.Adapter<MyScheduleAdapter.ViewHolder> {
private static final String TAG = "MyScheduleTwoAdapter";
private ArrayList<GetDoctorScheduleDetail> getDoctorScheduleDetails;
private ArrayList<GetBlockedTimings> getBlockedTimingses = new ArrayList<>();
private ArrayList<AvailableTimeSlots> availableTimeSlotses = new ArrayList<>();
Context context;
private LayoutInflater inflater = null;
private int mSelectedItemPosition = -1;
Activity parentActivity;
ProgressDialog pd;
int fk_time_id;
int fk_schedule_id;
int fkscheduleid;
int getFk_schedule_id;
int block_time_slot_id;
int time_slot_id;
String DateofSlot;
String BlockDateOfSlot;
int blockid;
SessionManager manager = new SessionManager();
int Doc_Id;
ArrayList<Integer> compare= new ArrayList<Integer>();
ArrayList<Integer> compare_fk= new ArrayList<Integer>();
public MyScheduleAdapter(Context context, ArrayList<GetDoctorScheduleDetail> getDoctorScheduleDetails) {
this.context = context;
this.getDoctorScheduleDetails = getDoctorScheduleDetails;
inflater = LayoutInflater.from(context);
// setHasStableIds(true);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.row_item_get_doctor_schedule, parent, false);
MyScheduleAdapter.ViewHolder holder = new MyScheduleAdapter.ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
final GetDoctorScheduleDetail pojo = getDoctorScheduleDetails.get(position);
fkscheduleid = pojo.getScheduleId();
DateofSlot = pojo.getDateOfSlot();
try {
Doc_Id = manager.getPreferencesInt(context, "DocId");
Log.e(TAG, "DOCID" + Doc_Id);
holder.bindDataWithViewHolder(pojo, position);
//getting data from availavle timeslots
holder.tv_time_of_slot.setText(pojo.getAvailableTimeSlots().get(position).getTimeOfSlot());
time_slot_id = pojo.getAvailableTimeSlots().get(position).getTimeSlotId();
//want to ge
block_time_slot_id = pojo.getGetBlockedTimings().get(position).getFkTimeId();
BlockDateOfSlot = pojo.getGetBlockedTimings().get(position).getBlockDateOfSlot();
blockid = pojo.getGetBlockedTimings().get(position).getBlockId();
Log.e(TAG, "values_blockk" + time_slot_id +" "+ block_time_slot_id);
compare.add(time_slot_id);//compare is an arraylist using to save Availablearray-->timeslot id
compare_fk.add(block_time_slot_id);//compare_fk is an arraylist using to save getblocktimeid-->fktime id
Log.e(TAG, "compare" + compare);
Log.e(TAG, "compare_fk" + compare_fk);
/*erlier I was using this*/
/*ArrayList<Integer> x = compare;
ArrayList<Integer> y = compare_fk;
for (int i = 0; i < x.size(); i++) {
Integer xval = y.get(i);
for (int j = 0; j < y.size(); j++) {
if (xval.equals(x.get(j))) {
Toast.makeText(context,"same_list"+y.get(j),Toast.LENGTH_SHORT).show();
holder.tv_time_of_slot.setTextColor(Color.RED);
}
}
}*/
int array1Size = compare.size();
int array2Size = compare_fk.size();
if (compare.size() > compare_fk.size()) {
int k = 0;
for (int i = 0; i < compare_fk.size(); i++) {
if (((Integer)compare.get(i)).equals((Integer)compare_fk.get(i))) {
System.out.println((Integer)compare_fk.get(i));
Log.e("values_adapter", String.valueOf(((Integer)compare_fk.get(i))));
}
k = i;
}
}
else {
int k = 0;
for (int i = 0; i < compare.size(); i++) {
if (((Integer)compare.get(i)).equals((Integer) compare_fk.get(i))) {
System.out.println((Integer) compare.get(i));
Log.e("values_adapter11",String.valueOf(((Integer)compare.get(i))));
}
k = i;
}
}
if (time_slot_id == block_time_slot_id)
{
holder.tv_time_of_slot.setTextColor(Color.RED);
}
if (!(pojo.getGetBlockedTimings().get(position).getBlockDateOfSlot().equals("")))
{
holder.tv_d.setText(pojo.getGetBlockedTimings().get(position).getBlockDateOfSlot());
holder.tv_b.setText(pojo.getGetBlockedTimings().get(position).getBlockId());
}
} catch (Exception e) {
e.printStackTrace();
e.getMessage();
}
// //iterate on the general list
// for (int i = 0; i < availableTimeSlotses.size(); i++) {
// int timeSlotId = availableTimeSlotses.get(i).getTimeSlotId();
// if (getFk_time_id == timeSlotId) {
//
// holder.tv_time_of_slot.setText(pojo.getDateOfSlot());
// }
// }
// block api
holder.btn_block.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog lDialog = new Dialog(context);
lDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
lDialog.setCancelable(false);
lDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
lDialog.getWindow().setDimAmount(.7f);
lDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
lDialog.getWindow().setElevation(4);
}
lDialog.setContentView(R.layout.popup_no_yes);
TextView tv_titiel = (TextView) lDialog.findViewById(R.id.tv_titiel);
TextView textMsg = (TextView) lDialog.findViewById(R.id.popup_msgs);
Button btnno = (Button) lDialog.findViewById(R.id.popup_no_btn);
Button btnyes = (Button) lDialog.findViewById(R.id.popup_yes_btn);
btnno.setTransformationMethod(null);
btnyes.setTransformationMethod(null);
tv_titiel.setText("Schedule");
textMsg.setText("Are you sure you want to block this slot?");
btnno.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
lDialog.dismiss();
}
});
btnyes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("notification_fragment"));
slotBlockingApi(fkscheduleid, time_slot_id);
lDialog.dismiss();
}
});
lDialog.show();
}
});
}
#Override
public int getItemCount() {
return getDoctorScheduleDetails.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
public void slotBlockingApi(int _fk_schedule_id, int _fk_time_id) {
isOnline();
pd = createProgressDialog(context);
pd.show();
final String requestBody = "'{\"fkScheduledId\":\"" + _fk_schedule_id +
"\",\"fkTimeId\":\"" + _fk_time_id +
"\",\"DoctorId\":\"" + Doc_Id +
"\"}'";
Log.e(TAG, "requset body of slotBlockingApi : " + requestBody);
NetworkManager.getInstance(context).makeNetworkRequestForJSON(
Request.Method.POST,
Common.BASE_URL + "/PostDoctorCheckForAppointmentBeforeSlotBlocking",
null,
requestBody,
null,
new NetworkResponseListenerJSONObject() {
#Override
public void onDataReceived(Object data) {
pd.dismiss();
Log.e(TAG, "response of slotBlockingApi : " + data.toString());
try {
JSONObject jsonObject = new JSONObject(data.toString());
JSONObject ResponseJsonObject1 = jsonObject.getJSONObject("Response");
int ResponseCode = ResponseJsonObject1.getInt("ResponseCode");
String ResponseText = ResponseJsonObject1.getString("ResponseText");
// JSONObject jsonObjectDetail = jsonObject.getJSONObject("Detail");
// Log.e(TAG, "jsonObjectDetail : " + jsonObjectDetail);
// int doc_id = jsonObjectDetail.getInt("DocId");
// if (ResponseText == "No Appointment" || ResponseText.equals("No Appointment") || ResponseText.equalsIgnoreCase("No Appointment")) {
if (ResponseText == "No Appointment" || ResponseText.equals("No Appointment") || ResponseText.equalsIgnoreCase("No Appointment")) {
// if (ResponseText =="No Appointment" || ResponseText.equals("No Appointment")) {
pd = createProgressDialog(context);
pd.show();
final String requestBody = "'{\"utcTimeOffset\":\"" + "330" +
"\",\"BlockedScheduledDate\":\"" + DateofSlot +
"\",\"fkScheduledId\":\"" + fkscheduleid +
"\",\"fkTimeId\":\"" + time_slot_id +
"\"}'";
Log.e(TAG, "requset body of slotBlocking: " + requestBody);
NetworkManager.getInstance(context).makeNetworkRequestForJSON(
Request.Method.POST,
Common.BASE_URL + "/PostDoctorBlockTimeSlot",
null,
requestBody,
null,
new NetworkResponseListenerJSONObject() {
#Override
public void onDataReceived(Object data) {
pd.dismiss();
new ShowMessage(context, "Block Slot","Time slot blocked Successfully");
Log.e(TAG, "response of slotBlocking: " + data.toString());
}
#Override
public void onDataFailed(VolleyError error) {
pd.dismiss();
String json = null;
NetworkResponse response = error.networkResponse;
if (response != null && response.data != null) {
switch (response.statusCode) {
case 302:
Toast.makeText(context, "No Internet Connection Found.", Toast.LENGTH_SHORT).show();
break;
}
//Additional cases
}
}
});
} else {
final Dialog lDialog = new Dialog(context);
lDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
lDialog.setCancelable(false);
lDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
lDialog.getWindow().setDimAmount(.7f);
lDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
lDialog.getWindow().setElevation(4);
}
lDialog.setContentView(R.layout.custom_popup);
TextView textTitle = (TextView) lDialog.findViewById(R.id.popup_title);
TextView textMsg = (TextView) lDialog.findViewById(R.id.popup_msg);
Button okButton = (Button) lDialog.findViewById(R.id.popup_ok_btn);
okButton.setTransformationMethod(null);
textTitle.setText("Schedule");
textMsg.setText("An appointment has been booked on this slot.");
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
lDialog.dismiss();
}
});
lDialog.show();
}
// else if (ResponseCode == 0 || ResponseCode == 2) {
// new ShowMessage(context, ResponseText);
// }
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onDataFailed(VolleyError error) {
pd.dismiss();
String json = null;
NetworkResponse response = error.networkResponse;
if (response != null && response.data != null) {
switch (response.statusCode) {
case 302:
Toast.makeText(context, "No Internet Connection Found.", Toast.LENGTH_SHORT).show();
break;
}
//Additional cases
}
}
});
}
public boolean isOnline() {
ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
if (netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()) {
new ShowMessage(context, "Network error","Internet not available, Cross check your internet connectivity and try again");
}
return true;
}
/**
* VIEW HOLDER CLASS DEFINE HERE
*/
public class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.ll_row_item_get_doctor_schedule)
LinearLayout ll_row_item_get_doctor_schedule;
#BindView(R.id.tv_time_of_slot)
TextView tv_time_of_slot;
#BindView(R.id.btn_block)
Button btn_block;
#BindView(R.id.btn_unblock)
Button btn_unblock;
#BindView(R.id.tv_d)
TextView tv_d;
#BindView(R.id.tv_b)
TextView tv_b;
GetDoctorScheduleDetail doctorScheduleDetail = null;
ItemClickListener clickListener;
private ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
ll_row_item_get_doctor_schedule.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Handling for background selection state changed
int previousSelectState = mSelectedItemPosition;
mSelectedItemPosition = getAdapterPosition();
//notify previous selected item
notifyItemChanged(previousSelectState);
//notify new selected Item
notifyItemChanged(mSelectedItemPosition);
//Your other handling in onclick
}
});
}
public void setClickListener(ItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
#OnClick
public void onClickMethod(View v) {
clickListener.onClick(v, getPosition(), false);
}
public void bindDataWithViewHolder(GetDoctorScheduleDetail schedulePojo, int currentPosition) {
this.doctorScheduleDetail = schedulePojo;
//Handle selection state in object View.
if (currentPosition == mSelectedItemPosition) {
btn_block.setVisibility(View.VISIBLE);
} else {
btn_block.setVisibility(View.GONE);
}
//other View binding logics like setting text , loading image etc.
}
}
}
I'm not android studio developer or java developer but regarding for my graduation project I need to make an android app that connects to HC-05 Bluetooth module "Arduino", then starts to transmit and receive bytes ... I have found a lot of projects that connects to the Bluetooth module by showing you a list of Bluetooth devices then you can choose which one you want to connect ...
but I don't want to use this method I want to find a method that searches for a specific Bluetooth mac address and if it available, start connecting to it, if it not available, the app will continue searching ...
I don't have any experience how can programmatically make this.
so please be patient :D
I have done the XML design...
I want to add the mac address connecting code here
package mdluex.smartx;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class ActivityControlCenter extends AppCompatActivity {
private int room1_str = 1;
private int room2_str = 0;
private int room3_str = 1;
private int room4_str = 1;
private int room5_str = 1;
private int room6_str = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_control_center);
final RelativeLayout room1_btn = (RelativeLayout) this.findViewById(R.id.room1_btn);
final TextView room1_st = (TextView) this.findViewById(R.id.room1_st);
final ImageView room1_img = (ImageView) this.findViewById(R.id.room1_img);
room1_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room1_str == 0){
room1_str = 1;
room1_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room1_st.setText("ON");
room1_img.setImageResource(R.drawable.lamp_on);
}
else {
room1_str = 0;
room1_btn.setBackgroundResource(R.drawable.btn_grid_off);
room1_st.setText("OFF");
room1_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room2_btn = (RelativeLayout) this.findViewById(R.id.room2_btn);
final TextView room2_st = (TextView) this.findViewById(R.id.room2_st);
final ImageView room2_img = (ImageView) this.findViewById(R.id.room2_img);
room2_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room2_str == 0){
room2_str = 1;
room2_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room2_st.setText("ON");
room2_img.setImageResource(R.drawable.lamp_on);
}
else {
room2_str = 0;
room2_btn.setBackgroundResource(R.drawable.btn_grid_off);
room2_st.setText("OFF");
room2_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room3_btn = (RelativeLayout) this.findViewById(R.id.room3_btn);
final TextView room3_st = (TextView) this.findViewById(R.id.room3_st);
final ImageView room3_img = (ImageView) this.findViewById(R.id.room3_img);
room3_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room3_str == 0){
room3_str = 1;
room3_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room3_st.setText("ON");
room3_img.setImageResource(R.drawable.lamp_on);
}
else {
room3_str = 0;
room3_btn.setBackgroundResource(R.drawable.btn_grid_off);
room3_st.setText("OFF");
room3_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room4_btn = (RelativeLayout) this.findViewById(R.id.room4_btn);
final TextView room4_st = (TextView) this.findViewById(R.id.room4_st);
final ImageView room4_img = (ImageView) this.findViewById(R.id.room4_img);
room4_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room4_str == 0){
room4_str = 1;
room4_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room4_st.setText("ON");
room4_img.setImageResource(R.drawable.lamp_on);
}
else {
room4_str = 0;
room4_btn.setBackgroundResource(R.drawable.btn_grid_off);
room4_st.setText("OFF");
room4_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room5_btn = (RelativeLayout) this.findViewById(R.id.room5_btn);
final TextView room5_st = (TextView) this.findViewById(R.id.room5_st);
final ImageView room5_img = (ImageView) this.findViewById(R.id.room5_img);
room5_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room5_str == 0){
room5_str = 1;
room5_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room5_st.setText("ON");
room5_img.setImageResource(R.drawable.lamp_on);
}
else {
room5_str = 0;
room5_btn.setBackgroundResource(R.drawable.btn_grid_off);
room5_st.setText("OFF");
room5_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room6_btn = (RelativeLayout) this.findViewById(R.id.room6_btn);
final TextView room6_st = (TextView) this.findViewById(R.id.room6_st);
final ImageView room6_img = (ImageView) this.findViewById(R.id.room6_img);
room6_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room6_str == 0){
room6_str = 1;
room6_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room6_st.setText("ON");
room6_img.setImageResource(R.drawable.lamp_on);
}
else {
room6_str = 0;
room6_btn.setBackgroundResource(R.drawable.btn_grid_off);
room6_st.setText("OFF");
room6_img.setImageResource(R.drawable.lamp_off);
}
}
});
}
}
this is the XML design
Activity Design
the full project code on GitHub
I found the solution :D
thanks, guys ...
My full project contains this code:
package mdluex.smartx;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class ActivityControlCenter extends AppCompatActivity {
private int room1_str = 1;
private int room2_str = 0;
private int room3_str = 1;
private int room4_str = 1;
private int room5_str = 1;
private int room6_str = 1;
String deviceName = "HC-05";
BluetoothDevice result = null;
BluetoothAdapter bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
private BluetoothSocket socket;
private OutputStream outputStream;
private InputStream inputStream;
private final UUID PORT_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");//Serial Port Service ID
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_control_center);
if (bluetoothAdapter == null) {
Toast.makeText(getApplicationContext(),"Device doesnt Support Bluetooth",Toast.LENGTH_SHORT).show();
}
if(!bluetoothAdapter.isEnabled())
{
Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableAdapter, 0);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Set<BluetoothDevice> devices = bluetoothAdapter.getBondedDevices();
if (devices != null) {
for (BluetoothDevice device : devices) {
if (deviceName.equals(device.getName())) {
Toast.makeText(getApplicationContext(),"SamrtX is available ",Toast.LENGTH_SHORT).show();
result = device;
boolean connected=true;
try {
socket = result.createRfcommSocketToServiceRecord(PORT_UUID);
socket.connect();
Toast.makeText(getApplicationContext(),"Connected",Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
connected=false;
Toast.makeText(getApplicationContext(),"SamrtX is not available ",Toast.LENGTH_SHORT).show();
}
if(connected)
{
try {
outputStream=socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream=socket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
break;
}
}
}
final RelativeLayout room1_btn = (RelativeLayout) this.findViewById(R.id.room1_btn);
final TextView room1_st = (TextView) this.findViewById(R.id.room1_st);
final ImageView room1_img = (ImageView) this.findViewById(R.id.room1_img);
room1_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room1_str == 0){
room1_str = 1;
if (socket!=null)
{
try
{
socket.getOutputStream().write("a".toString().getBytes());
}
catch (IOException e)
{
Toast.makeText(getApplicationContext(),"Error ",Toast.LENGTH_SHORT).show();
}
}
room1_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room1_st.setText("ON");
room1_img.setImageResource(R.drawable.lamp_on);
}
else {
room1_str = 0;
if (socket!=null)
{
try
{
socket.getOutputStream().write("b".toString().getBytes());
}
catch (IOException e)
{
Toast.makeText(getApplicationContext(),"Error ",Toast.LENGTH_SHORT).show();
}
}
room1_btn.setBackgroundResource(R.drawable.btn_grid_off);
room1_st.setText("OFF");
room1_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room2_btn = (RelativeLayout) this.findViewById(R.id.room2_btn);
final TextView room2_st = (TextView) this.findViewById(R.id.room2_st);
final ImageView room2_img = (ImageView) this.findViewById(R.id.room2_img);
room2_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room2_str == 0){
room2_str = 1;
room2_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room2_st.setText("ON");
room2_img.setImageResource(R.drawable.lamp_on);
}
else {
room2_str = 0;
room2_btn.setBackgroundResource(R.drawable.btn_grid_off);
room2_st.setText("OFF");
room2_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room3_btn = (RelativeLayout) this.findViewById(R.id.room3_btn);
final TextView room3_st = (TextView) this.findViewById(R.id.room3_st);
final ImageView room3_img = (ImageView) this.findViewById(R.id.room3_img);
room3_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room3_str == 0){
room3_str = 1;
room3_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room3_st.setText("ON");
room3_img.setImageResource(R.drawable.lamp_on);
}
else {
room3_str = 0;
room3_btn.setBackgroundResource(R.drawable.btn_grid_off);
room3_st.setText("OFF");
room3_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room4_btn = (RelativeLayout) this.findViewById(R.id.room4_btn);
final TextView room4_st = (TextView) this.findViewById(R.id.room4_st);
final ImageView room4_img = (ImageView) this.findViewById(R.id.room4_img);
room4_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room4_str == 0){
room4_str = 1;
room4_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room4_st.setText("ON");
room4_img.setImageResource(R.drawable.lamp_on);
}
else {
room4_str = 0;
room4_btn.setBackgroundResource(R.drawable.btn_grid_off);
room4_st.setText("OFF");
room4_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room5_btn = (RelativeLayout) this.findViewById(R.id.room5_btn);
final TextView room5_st = (TextView) this.findViewById(R.id.room5_st);
final ImageView room5_img = (ImageView) this.findViewById(R.id.room5_img);
room5_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room5_str == 0){
room5_str = 1;
room5_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room5_st.setText("ON");
room5_img.setImageResource(R.drawable.lamp_on);
}
else {
room5_str = 0;
room5_btn.setBackgroundResource(R.drawable.btn_grid_off);
room5_st.setText("OFF");
room5_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room6_btn = (RelativeLayout) this.findViewById(R.id.room6_btn);
final TextView room6_st = (TextView) this.findViewById(R.id.room6_st);
final ImageView room6_img = (ImageView) this.findViewById(R.id.room6_img);
room6_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room6_str == 0){
room6_str = 1;
room6_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room6_st.setText("ON");
room6_img.setImageResource(R.drawable.lamp_on);
}
else {
room6_str = 0;
room6_btn.setBackgroundResource(R.drawable.btn_grid_off);
room6_st.setText("OFF");
room6_img.setImageResource(R.drawable.lamp_off);
}
}
});
}
}
Hi there i've been constructing this code for a week but i still cant get it to work. It has no errors but when i run it on the AVD it terminates suddenly.
package com.tryout.sample;
import java.util.Random;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.app.Activity;
public class MainActivity extends Activity implements View.OnClickListener{
Random number = new Random();
int Low = 1;
int High = 13;
int RandomNumber = number.nextInt(High-Low) + Low;
int current = 0;
int points=0;
final Integer[] cardid = { R.drawable.card1,
R.drawable.card10,
R.drawable.card11,
R.drawable.card12,
R.drawable.card13,
R.drawable.card2,
R.drawable.card3,
R.drawable.card4,
R.drawable.card5,
R.drawable.card6,
R.drawable.card7,
R.drawable.card8,
R.drawable.card9,
};
ImageView pic2 = (ImageView) findViewById(R.id.imageView1);
final TextView score = (TextView) findViewById(R.id.textView2);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView score = (TextView) findViewById(R.id.textView2);
Button high = (Button) findViewById(R.id.button1);
Button low = (Button) findViewById(R.id.button2);
final ImageView pic = (ImageView) findViewById(R.id.imageView1);
low.setOnClickListener(new view.OnClickListener() {
public void onClick(View v) {
int resource = cardid[RandomNumber];
if(current < RandomNumber){
points = points + 1;
score.setText(points);
pic.setImageResource(resource);
}else{
score.setText("Game Over");
}
}
});
high.setOnClickListener(new View.OnClickListener() {
public void higher(View v) {
int resource = cardid[RandomNumber];
if(current > RandomNumber){
points = points + 1;
score.setText(points);
pic.setImageResource(resource);
}else{
score.setText("Game Over");
}
}
});
int resource = cardid[RandomNumber];
pic.setImageResource(resource);
current = RandomNumber;
}
}
I cant figure out where my problem is, kindly check out my code. THanks for any help
put this:
ImageView pic2 = (ImageView) findViewById(R.id.imageView1);
final TextView score = (TextView) findViewById(R.id.textView2);
in you onCreate method after the call setContentView(R.layout.activity_main);.
How should R.id.imageView1 assigned if the content is not specified like in your case?
ImageView pic2;
TextView score;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pic2 = (ImageView) findViewById(R.id.imageView1);
score = (TextView) findViewById(R.id.textView2);
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
public class minigame_cardpairing extends Activity implements View.OnClickListener {
private static final int TOTAL_CARD_NUM = 16;
private int[] cardId = {R.id.card01, R.id.card02, R.id.card03, R.id.card04, R.id.card05, R.id.card06, R.id.card07, R.id.card08,
R.id.card09, R.id.card10, R.id.card11, R.id.card12, R.id.card13, R.id.card14, R.id.card15, R.id.card16};
private Card[] cardArray = new Card[TOTAL_CARD_NUM];
private int CLICK_CNT = 0;
private Card first, second;
private int SUCCESS_CNT = 0;
private boolean INPLAY = false;
//----------- Activity widget -----------//
private Button start;
//-----------------------------------//
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.minigame_cardpairing);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
for(int i=0; i<TOTAL_CARD_NUM; i++) {
cardArray[i] = new Card(i/2);
findViewById(cardId[i]).setOnClickListener(this);
cardArray[i].card = (ImageButton) findViewById(cardId[i]); // Card assignment
cardArray[i].onBack();
}
start = (Button) findViewById(R.id.start);
start.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startGame();
//start.setBackgroundDrawable(background);
}
});
findViewById(R.id.exit).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setResult(RESULT_OK);
finish();
}
});
} // end of onCreate
protected void startDialog() {
AlertDialog.Builder alt1 = new AlertDialog.Builder(this);
alt1.setMessage("The match-card game. Please remember to flip the cards two by two card hand is a pair Hit. Hit all pairs are completed.")
.setCancelable(false)
.setPositiveButton("close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alt2 = alt1.create();
alt2.setTitle("Game Description");
alt2.show();
}
protected void clearDialog() {
AlertDialog.Builder alt1 = new AlertDialog.Builder(this);
alt1.setMessage("It fits all the cards in pairs. Congratulations.")
.setCancelable(false)
.setPositiveButton("close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alt2 = alt1.create();
alt2.setTitle("Match-complete");
alt2.show();
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
startDialog();
}
public void onClick(View v) {
if (INPLAY) {
switch (CLICK_CNT) {
case 0:
for (int i=0; i<TOTAL_CARD_NUM; i++) {
if (cardArray[i].card == (ImageButton) v) {
first = cardArray[i];
break;
}
}
if (first.isBack) {
first.onFront();
CLICK_CNT = 1;
}
break;
case 1:
for (int i=0; i<TOTAL_CARD_NUM; i++) {
if (cardArray[i].card == (ImageButton) v) {
second = cardArray[i];
break;
}
}
if (second.isBack) {
second.onFront();
if (first.value == second.value) {
SUCCESS_CNT++;
Log.v("SUCCESS_CNT", "" + SUCCESS_CNT);
if (SUCCESS_CNT == TOTAL_CARD_NUM/2) {
clearDialog();
}
}
else {
Timer t = new Timer(0);
t.start();
}
CLICK_CNT = 0;
}
break;
}
}
}
void startGame() {
int[] random = new int[TOTAL_CARD_NUM];
int x;
for (int i=0; i<TOTAL_CARD_NUM; i++) {
if (!cardArray[i].isBack)
cardArray[i].onBack();
}
boolean dup;
for (int i=0; i<TOTAL_CARD_NUM; i++) {
while(true) {
dup = false;
x = (int) (Math.random() * TOTAL_CARD_NUM);
for (int j=0; j<i; j++) {
if (random[j] == x) {
dup = true;
break;
}
}
if (!dup) break;
}
random[i] = x;
}
start.setClickable(false);
for (int i=0; i<TOTAL_CARD_NUM; i++) {
cardArray[i].card = (ImageButton) findViewById(cardId[random[i]]);
cardArray[i].onFront();
}
Log.v("timer", "start");
Timer t = new Timer(1);
//flag = false;
t.start();
/*
while(true) {
if (flag) break;
//Log.v("flag", "" + flag);
}
Log.v("timer", "end");
*/
SUCCESS_CNT = 0;
CLICK_CNT = 0;
INPLAY = true;
}
class Timer extends Thread {
int kind;
Timer (int kind) {
super();
this.kind = kind;
}
#Override
public void run() {
INPLAY = false;
// TODO Auto-generated method stub
try {
if (kind == 0) {
Thread.sleep(1000);
mHandler.sendEmptyMessage(0);
}
else if (kind == 1) {
Thread.sleep(3000);
mHandler.sendEmptyMessage(1);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
INPLAY = true;
}
}
Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 0) {
first.onBack();
second.onBack();
first.isBack = true;
second.isBack = true;
}
else if (msg.what == 1) {
//flag = true;
for (int i=0; i<TOTAL_CARD_NUM; i++) {
cardArray[i].onBack();
}
start.setClickable(true);
}
}
};
}
class Card { // start of Card class
private final static int backImageID = R.drawable.cardback;
private final static int[] frontImageID = {R.drawable.card1, R.drawable.card2,
R.drawable.card3, R.drawable.card4,
R.drawable.card5, R.drawable.card6,
R.drawable.card7, R.drawable.card8};
int value;
boolean isBack;
ImageButton card;
Card(int value) {
this.value = value;
}
public void onBack() {
if (!isBack) {
card.setBackgroundResource(backImageID);
isBack = true;
}
}
public void flip() {
if (!isBack) {
card.setBackgroundResource(backImageID);
isBack = true;
}
else {
card.setBackgroundResource(frontImageID[value]);
isBack = false;
}
}
public void onFront() {
if (isBack) {
card.setBackgroundResource(frontImageID[value]);
isBack = false;
}
}
} // end of Card class
Im following the tutorial of In-app Billing from the following link:
Android Studio Google Play In-app Billing Tutorial.
Im implementing this logic in a Contact Adapter class which extends Base Adapter. In tutorial it is implemented in a class which extends Activity.
Error comes on onActivityResult(). I read several questions on this and I understand this method should be written in class which extends Activity but in my case the scenario is different.
Is there any way to solve this without writing onActivityResult method in MainActivity class.. and if not what should I do?
Heres ContactAdapter.java
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import com.neirx.myco.smsproject.util.IabHelper;
import com.neirx.myco.smsproject.util.IabResult;
import com.neirx.myco.smsproject.util.Inventory;
import com.neirx.myco.smsproject.util.Purchase;
import java.util.List;
public class ContactAdapter extends BaseAdapter {
private static final java.lang.String CLASS_NAME = "<ContactAdapter> ";
Context context;
List<Contact> objects;
LayoutInflater lInflater;
MainActivity activity;
static final String ITEM_SKU = "android.test.purchased";
IabHelper mHelper;
int count = 0;
int get_limit;
private int limit_counter = 0;
private int max_limit = 2;
boolean testbool = true;
public ContactAdapter(Context context, List<Contact> contact) {
this.context = context;
objects = contact;
lInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
activity = (MainActivity) context;
}
#Override
public int getCount() {
int selectedCount = 0;
int nonSelectedCount = 0;
int size = 0;
for(Contact contact : objects){
if(contact.isChecked()) selectedCount++;
else nonSelectedCount++;
}
if(activity.isShowSelected()) size += selectedCount;
if(activity.isShowNonSelected()) size += nonSelectedCount;
return size;
}
#Override
public Object getItem(int position) {
return objects.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public void buyClick() {
mHelper.launchPurchaseFlow(activity, ITEM_SKU, 10001, mPurchaseFinishedListener, "mypurchasetoken");
}
#Override
protected void onActivityResult(int requestCode, int resultCode,Intent data)
{
if (!mHelper.handleActivityResult(requestCode,resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
}
}
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result,Purchase purchase)
{
if (result.isFailure()) {
// Handle error
Log.d("----FAILURE 1---", "FAIL 1");
return;
}
else if (purchase.getSku().equals(ITEM_SKU)) {
consumeItem();
//buyButton.setEnabled(false);
}
}
};
public void consumeItem() {
mHelper.queryInventoryAsync(mReceivedInventoryListener);
}
IabHelper.QueryInventoryFinishedListener mReceivedInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result,Inventory inventory) {
if (result.isFailure()) {
// Handle failure
Log.d("----FAILURE 2---", "FAIL 2");
} else {
mHelper.consumeAsync(inventory.getPurchase(ITEM_SKU),mConsumeFinishedListener);
}
}
};
IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener() {
public void onConsumeFinished(Purchase purchase,IabResult result) {
if (result.isSuccess()) {
//clickButton.setEnabled(true);
Log.d("----Success ----", "Success");
} else {
// handle error
Log.d("----FAILURE 3---", "FAIL 3");
}
}
};
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
String base64EncodedPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxW650UixX2dLFECVdOpTh5OpBTqHwsznQAKd/cVcqKhrXROy4+Gj6B7M6wbkhTaloNSzTOf+nw9t1LZZ19Vlr6kcwmtxP+V/HOFwjf/NB69StOONogXtGKDyRrxtVaPM5es3yGy/aP/LXWfTLFQYJvur4AePonuRXz33iufBq5ITDQJ0+0D/o/mGtadJv0ZMsP9LV/qrMqruoqpSdaIiw5TGXdzYlJTuoP3GwS9kRyZKDeG/70KZ28W/ZclVWAdnZ7aCeDURYDV3a4pmGp5/cIvKwbex6Y7KbQYENX5ObSgNoFHLdyPTdkYaeuU9O6pet2TjGUCKr8n4M5KUMZVm8QIDAQAB";
mHelper = new IabHelper(context, base64EncodedPublicKey);
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result)
{
if (!result.isSuccess()) {
Log.d("---MY TAG---", "In-app Billing setup failed: " +
result);
} else {
Log.d("---MY TAG---", "In-app Billing is set up OK");
}
}
});
SharedPreferences limit_pref = context.getSharedPreferences(Statical.PREF_LIMIT, Context.MODE_PRIVATE);
get_limit = limit_pref.getInt("LIMIT_KEY",0);
//Log.d("----- STORED VALUE-----", "Value is: "+get_limit);
Log.d("----- Max VALUE-----", "Value is: "+max_limit);
if (view == null) {
view = lInflater.inflate(R.layout.view_contact, parent, false);//create view file
}
if (position == 0) {
count = 0;
}
if (!activity.isShowSelected()) {
while (objects.get(position + count).isChecked()) {
count++;
}
}
if (!activity.isShowNonSelected()) {
while (!objects.get(position + count).isChecked()) {
count++;
}
}
final Contact contact = objects.get(position + count);
String contactFirstName = contact.getFirstName();
String contactSecondName = contact.getSecondName();
String contactMiddleName = contact.getMiddleName();
String[] contactNumbers = contact.getNumbers();
TextView tvName = (TextView) view.findViewById(R.id.tvName);
TextView tvNumber = (TextView) view.findViewById(R.id.tvNumber);
final CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBox);
if(get_limit == max_limit)
{
//checkBox.setChecked(contact.isChecked());
//testbool = false;
limit_counter = get_limit;
}
else if (get_limit == 1)
{
limit_counter = 1;
}
String fullName;
switch (MainActivity.sortMode) {
case Contact.COMPARE_SECOND_NAME:
fullName = getFullName(contactSecondName, contactFirstName);
break;
case Contact.COMPARE_MIDDLE_NAME:
fullName = getFullName(contactMiddleName, contactFirstName, contactSecondName);
break;
default:
fullName = getFullName(contactFirstName, contactSecondName);
break;
}
tvName.setText(fullName);
StringBuilder sbNumber = new StringBuilder();
for (int i = 0; i < contactNumbers.length; i++) {
sbNumber.append(contactNumbers[i]);
if (i < contactNumbers.length - 1) {
sbNumber.append(", ");
}
}
tvNumber.setText(sbNumber);
if (testbool) {
//Log.d("Check Boolean Tag 2 ", "testbool: "+testbool);
checkBox.setChecked(contact.isChecked());
}
checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences selected = context.getSharedPreferences(Statical.CONTACTS_SELECTED, Context.MODE_PRIVATE);
SharedPreferences.Editor editSelected = selected.edit();
SharedPreferences limit_pref = context.getSharedPreferences(Statical.PREF_LIMIT, Context.MODE_PRIVATE);
SharedPreferences.Editor edit_limit_pref = limit_pref.edit();
int k = 0;
if(limit_counter == max_limit)
{
checkBox.setChecked(false);
//Toast.makeText(context,"Limit reached !! ", Toast.LENGTH_SHORT).show();
Log.d("-------LIMIT REACH-----", "value: "+limit_counter);
edit_limit_pref.putInt("LIMIT_KEY",limit_counter);
showAlertDialog();
}
if (contact.isChecked() && limit_counter <= max_limit && limit_counter >= 0) {
limit_counter = limit_counter - 1;
editSelected.putBoolean(contact.getContactId(), false);
edit_limit_pref.putInt("LIMIT_KEY",limit_counter);
contact.setChecked(false);
Log.d("-------UN CHECKED-----", "Un Checked value: "+limit_counter);
k = -1;
}
else if(!contact.isChecked() && limit_counter < max_limit){
limit_counter = limit_counter + 1;
editSelected.putBoolean(contact.getContactId(), true);
edit_limit_pref.putInt("LIMIT_KEY",limit_counter);
contact.setChecked(true);
Log.d("------- CHECKED -----", "Checked value: "+limit_counter);
k = 1;
}
editSelected.apply();
edit_limit_pref.apply();
activity.updateCount(k);
}
});
return view;
}
public void showAlertDialog()
{
Log.d("-------VALUE-----", "value: "+limit_counter);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("Limit Reached!");
alertDialog.setMessage("Buy Pro Version");
alertDialog.setIcon(R.drawable.action_bar_logo);
alertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
buyClick();
Log.d("-------OK PRESSED -----", "value: " + limit_counter);
dialog.cancel();
}
});
alertDialog.setNegativeButton("Later", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.d("----LATER PRESSED -----", "value: " + limit_counter);
dialog.cancel();
}
});
alertDialog.show();
}
private String getFullName(String first, String second, String third) {
StringBuilder sbName = new StringBuilder();
if (!first.isEmpty()) {
sbName.append(first).append(" ");
}
if (!second.isEmpty()) {
sbName.append(second).append(" ");
}
if (!third.isEmpty()) {
sbName.append(third);
}
return sbName.toString();
}
private String getFullName(String first, String second) {
StringBuilder sbName = new StringBuilder();
if (!first.isEmpty()) {
sbName.append(first).append(" ");
}
if (!second.isEmpty()) {
sbName.append(second);
}
return sbName.toString();
}
}
I recommend you to create an activity just to process this payment and then you can back to your normal flow.
In this code I have an if else block. In the if else I want to include a button using bundle but I have tried and I get an error. My code is below, does anyone have any ideas why I am getting the error?
package com.apps.visitkuningan;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class KetWisata extends Activity{
Intent iinntteen;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.ket_wisata);
String tampil = getIntent().getExtras().getString("key");
ImageView img1 = (ImageView) findViewById(R.id.wisata);
TextView nama = (TextView) findViewById(R.id.nama);
TextView alamat = (TextView) findViewById(R.id.alamat);
TextView keterangan = (TextView) findViewById(R.id.keterangan);
Button arahkan = (Button) findViewById(R.id.arahkan);
final Bundle bundel2 = new Bundle();
final String tampil2 = null;
arahkan.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
bundel2.putString("key", tampil2);
iinntteen.putExtras(bundel2);
startActivity(iinntteen);
}
});
if(tampil.equalsIgnoreCase("wis_balongdalem"))
{
img1.setBackgroundResource(R.drawable.wis_balong);
nama.setText("Balong Dalem");
alamat.setText(R.string.add_balong);
keterangan.setText(R.string.ket_balong);
iinntteen = new Intent(KetWisata.this, Arahkan.class);
tampil2 ="coba"; //TAMPIL2 CANT DETECTED..
}
if(tampil.equalsIgnoreCase("wis_curugbangkong"))
{
img1.setBackgroundResource(R.drawable.wis_bangkong2);
nama.setText("Curug Bangkong");
alamat.setText(R.string.add_bangkong);
keterangan.setText(R.string.ket_bangkong);
iinntteen = new Intent(KetWisata.this, Tentang.class);
}
if(tampil.equalsIgnoreCase("wis_buperciberem"))
{
img1.setBackgroundResource(R.drawable.wis_ciberem2);
nama.setText("Buper Cibeureum");
alamat.setText(R.string.add_ciberem);
keterangan.setText(R.string.ket_ciberem);
}
if(tampil.equalsIgnoreCase("wis_cibulan"))
{
img1.setBackgroundResource(R.drawable.wis_cibulan2);
nama.setText("Kolam Cibulan");
alamat.setText(R.string.add_cibulan);
keterangan.setText(R.string.ket_cibulan);
}
if(tampil.equalsIgnoreCase("wis_balongcicerem"))
{
img1.setBackgroundResource(R.drawable.wis_balong);
nama.setText("Balong Cicereum");
alamat.setText(R.string.add_cicerem);
keterangan.setText(R.string.ket_cicerem);
}
if(tampil.equalsIgnoreCase("wis_balongcigugur"))
{
img1.setBackgroundResource(R.drawable.wis_cigugur2);
nama.setText("Balong Cigugur");
alamat.setText(R.string.add_cigugur);
keterangan.setText(R.string.ket_cigugur);
}
if(tampil.equalsIgnoreCase("wis_curugcilengkrang"))
{
img1.setBackgroundResource(R.drawable.wis_cilengkrang2);
nama.setText("Lembah Cilengkrang");
alamat.setText(R.string.add_cilengkrang);
keterangan.setText(R.string.ket_cilengkrang);
}
if(tampil.equalsIgnoreCase("wis_cipari"))
{
img1.setBackgroundResource(R.drawable.wis_cipari2);
nama.setText("Taman Purbakala Cipari");
alamat.setText(R.string.add_cipari);
keterangan.setText(R.string.ket_cipari);
}
if(tampil.equalsIgnoreCase("wis_balongdarmaloka"))
{
img1.setBackgroundResource(R.drawable.wis_darmaloka2);
nama.setText("Balong Darmaloka");
alamat.setText(R.string.add_darmaloka);
keterangan.setText(R.string.ket_darmaloka);
}
if(tampil.equalsIgnoreCase("wis_linggarjatiindah"))
{
img1.setBackgroundResource(R.drawable.wis_linggarjat2i);
nama.setText("Linggarjati Indah");
alamat.setText(R.string.add_linggarjati);
keterangan.setText(R.string.ket_linggarjati);
}
if(tampil.equalsIgnoreCase("wis_guamaria"))
{
img1.setBackgroundResource(R.drawable.wis_guamaria);
nama.setText("Gua Maria");
alamat.setText(R.string.add_guamaria);
keterangan.setText(R.string.ket_guamaria);
}
if(tampil.equalsIgnoreCase("wis_gedungnaskah"))
{
img1.setBackgroundResource(R.drawable.wis_muslinggar2);
nama.setText("Musium Linggarjati");
alamat.setText(R.string.add_naskah);
keterangan.setText(R.string.ket_naskah);
}
if(tampil.equalsIgnoreCase("wis_buperpalutungan"))
{
img1.setBackgroundResource(R.drawable.wis_palutungan2);
nama.setText("Buper Plautungan");
alamat.setText(R.string.add_palutungan);
keterangan.setText(R.string.ket_palutungan);
}
if(tampil.equalsIgnoreCase("wis_buperpaniis"))
{
img1.setBackgroundResource(R.drawable.wis_paniis2);
nama.setText("Buper Paniis");
alamat.setText(R.string.add_paniis);
keterangan.setText(R.string.ket_paniis);
}
if(tampil.equalsIgnoreCase("wis_paseban"))
{
img1.setBackgroundResource(R.drawable.wis_paseban);
nama.setText("Gedung Merapat Lima");
alamat.setText(R.string.add_paseban);
keterangan.setText(R.string.ket_paseban);
}
if(tampil.equalsIgnoreCase("wis_gedungsahrir"))
{
img1.setBackgroundResource(R.drawable.wis_gedungsut);
nama.setText("Gedung Sutan Syahrir");
alamat.setText(R.string.add_syahrir);
keterangan.setText(R.string.ket_syahrir);
}
if(tampil.equalsIgnoreCase("wis_sanggariang"))
{
img1.setBackgroundResource(R.drawable.wis_sanggariang2);
nama.setText("Kolam Renang Sanggariang");
alamat.setText(R.string.add_sanggariang);
keterangan.setText(R.string.ket_sanggariang);
}
if(tampil.equalsIgnoreCase("wis_sangkanurip"))
{
img1.setBackgroundResource(R.drawable.wis_sangkanurip2);
nama.setText("Pemandian Sangkanurip");
alamat.setText(R.string.add_sangkanurip);
keterangan.setText(R.string.ket_sangkanhurip);
}
if(tampil.equalsIgnoreCase("wis_curugsidomba"))
{
img1.setBackgroundResource(R.drawable.wis_sidomba2);
nama.setText("Sidomba");
alamat.setText(R.string.add_sidomba);
keterangan.setText(R.string.ket_sidomba);
}
if(tampil.equalsIgnoreCase("wis_talagaremis"))
{
img1.setBackgroundResource(R.drawable.wis_talagaremis);
nama.setText("Talagaremis");
alamat.setText(R.string.add_talagaremis);
keterangan.setText(R.string.ket_talagaremis); }
if(tampil.equalsIgnoreCase("wis_tngc"))
{
img1.setBackgroundResource(R.drawable.wis_tngc);
}
if(tampil.equalsIgnoreCase("wis_wadukdarma"))
{
img1.setBackgroundResource(R.drawable.wis_waduk2);
nama.setText("Waduk Darma");
alamat.setText(R.string.add_waduk);
keterangan.setText(R.string.ket_waduk);
}
if(tampil.equalsIgnoreCase("wis_abn"))
{
img1.setBackgroundResource(R.drawable.wis_abn);
}
if(tampil.equalsIgnoreCase("wis_hasanmaulana"))
{
img1.setBackgroundResource(R.drawable.wis_hasanmaulana);
nama.setText("Gedung Hasan Maulani");
alamat.setText(R.string.add_hasanmaulana);
keterangan.setText(R.string.ket_hasanmaulana);
}
if(tampil.equalsIgnoreCase("wis_makamvanbeck"))
{
img1.setBackgroundResource(R.drawable.wis_makamvanbeck);
nama.setText("Makam Van Beck");
alamat.setText(R.string.add_makamvanbeck);
keterangan.setText(R.string.ket_makamvanbeck);
}
if(tampil.equalsIgnoreCase("wis_situscangkuang"))
{
img1.setBackgroundResource(R.drawable.wis_situscangkuang);
nama.setText("Situs Cangkuang");
alamat.setText(R.string.add_cangkuang);
keterangan.setText(R.string.ket_cangkuang);
}
if(tampil.equalsIgnoreCase("wis_talaganilem"))
{
img1.setBackgroundResource(R.drawable.wis_talaganilem);
nama.setText("Talaganilem");
alamat.setText(R.string.add_talaganilem);
keterangan.setText(R.string.ket_talaganilem);
}
//arahkan.setOnClickListener(new OnClickListener() {
// #Override
// public void onClick(View arg0) {
// startActivity(new Intent(KetWisata.this, Arahkan.class));
// }
//});
}
}
Before doing this line:
getIntent().getExtras().ANYTHING_ELSE
Make sure that:
getIntent() != null && getIntent().getExtras() != null You can also check for getIntent().getExtras().isEmpty()