This is the code I have at the moment.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_earthbound);
int charNo = (Integer)getIntent().getExtras().get(EXTRA_CHARNO);
Earthbound character = Earthbound.chars[charNo];
ImageView photo = (ImageView) findViewById(R.id.photo);
photo.setImageResource(character.getImageResourceId());
photo.setContentDescription(character.getName());
TextView name = (TextView) findViewById(R.id.name);
name.setText(character.getName());
TextView desc = (TextView) findViewById(R.id.desc);
desc.setText(character.getDesc());
Button voice_btn = (Button)this.findViewById(R.id.voice_btn);
voice_btn.setContentDescription(character.getName());
final MediaPlayer mp = MediaPlayer.create(this, R.raw.snd_se_narration_characall_Ness);
final MediaPlayer mmp = MediaPlayer.create(this, R.raw.snd_se_narration_characall_Lucas);
voice_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
mp.start();
mmp.start();
}
});
I essentially have two activities, the first one being that the user can choose the list view option "Earthbound", a Java class which lists the characters, and an activity displaying the characters bio. The second activity has one button, but this button will change sounds depending on which character the user picked. This is where I am stuck.
This is the Java class if it helps:
private String name;
private String desc;
private int imageResourceId;
private int voiceId;
public Earthbound(String name, String desc, int imageResourceId, int voice){
this.name = name;
this.desc = desc;
this.imageResourceId = imageResourceId;
this.voiceId = voiceId;
}
public static final Earthbound[] chars = {
new Earthbound("Ness", "Ness is the silent main protagonist of EarthBound (Mother 2 in Japan), " +
"and is analogous to Ninten and Lucas in their respective games. He greatly enjoys baseball; " +
"not only are most of his weapons various types of baseball bats, " +
"but he can also equip several baseball caps. ", R.drawable.ness, R.raw.snd_se_narration_characall_Ness),
new Earthbound("Lucas", "Lucas is the central character of Mother 3, out of seven main characters total. " +
"(Lucas, Kumatora, Duster, Boney, Claus, Flint, and Salsa). He is from Tazmily Village. " +
"He is the gentle twin of Claus. ", R.drawable.lucas, R.raw.snd_se_narration_characall_Lucas),
};
public String getName() {
return name;
}
public String getDesc() {
return desc;
}
public int getImageResourceId() {
return imageResourceId;
}
#Override
public String toString() {
return this.name;
}
public int getVoiceId() {
return voiceId;
}
Can't you just use an if or switch statement to determine which sound plays?
if ((character.getName().compareTo("Ness")) == 0)
mp.start();
else
mmp.start();
something like this ought to work.
If you just need choose a sound to play, you can set your sound resource to you Earthbound, Others use your code and need not know which resource to selected.
private String name;
private String desc;
private int imageResourceId;
private int voiceId;
public Earthbound(String name, String desc, int imageResourceId, int voice){
this.name = name;
this.desc = desc;
this.imageResourceId = imageResourceId;
this.voiceId = voiceId;
}
public static final Earthbound[] chars = {
new Earthbound("Ness", "Ness is the silent main protagonist of EarthBound (Mother 2 in Japan), " +
"and is analogous to Ninten and Lucas in their respective games. He greatly enjoys baseball; " +
"not only are most of his weapons various types of baseball bats, " +
"but he can also equip several baseball caps. ", R.drawable.ness, R.raw.snd_se_narration_characall_Ness),
new Earthbound("Lucas", "Lucas is the central character of Mother 3, out of seven main characters total. " +
"(Lucas, Kumatora, Duster, Boney, Claus, Flint, and Salsa). He is from Tazmily Village. " +
"He is the gentle twin of Claus. ", R.drawable.lucas, R.raw.snd_se_narration_characall_Lucas),
};
public String getName() {
return name;
}
public String getDesc() {
return desc;
}
public int getImageResourceId() {
return imageResourceId;
}
#Override
public String toString() {
return this.name;
}
public int getVoiceId() {
return voiceId;
}
public int getMediaResourceId() {
return TextUtils.equals(name, "Ness") ? R.raw.snd_se_narration_characall_Ness : R.raw.snd_se_narration_characall_Lucas;
}
Then
final MediaPlayer mp = MediaPlayer.create(this, character.getMediaResourceId());
voice_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
mp.start();
}
});
Related
I've created a ListView (myList). By pressing on one of the items on the ListView, the app is supposed to direct the user to the PlaySongActivity page.
I used a searchById function to try to match the ID of the song and the song in my database.( get ID of the song and match the song ID in database to play the same song) However, my teacher told me I am searching by the ID of the ListView, not the song.
So is there any way I can either search by the song title or possibly add an ID to each item in the ListView?
I'm a beginner in coding and have searched for hours and found no solution on the internet :(
private SongCollection mySongCollection = new SongCollection();
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(SearchSong.this, PlaySongActivity.class);
String resourceId = AppUtil.getResourceId(SearchSong.this, myList);
Song selectedSong = mySongCollection.searchById(resourceId);
AppUtil.popMessage(SearchSong.this, "Streaming music: " + selectedSong.getTitle());
intent.putExtra("id", selectedSong.getId());
intent.putExtra("title", selectedSong.getTitle());
intent.putExtra("artiste", selectedSong.getArtiste());
intent.putExtra("fileLink", selectedSong.getFileLink());
intent.putExtra("coverArt", selectedSong.getCoverArt());
startActivity(intent);
}
});
SongCollection.class codes
package com.example.musix;
public class SongCollection {
private Song[] allSongs = new Song[9];
public SongCollection (){
prepareSongs();
}
private void prepareSongs(){
Song theWayYouLookTonight = new Song ("S1001", "The Way You Look Tonight", "Michael Buble", "a5b8972e764025020625bbf9c1c2bbb06e394a60?cid=2afe87a64b0042dabf51f37318616965", 4.66, "michael_buble_collection");
Song billiejean = new Song ("S1002", "Billie Jean", "Michael Jackson", "4eb779428d40d579f14d12a9daf98fc66c7d0be4?cid=2afe87a64b0042dabf51f37318616965", 4.9, "billie_jean");
Song somethingJustLikeThis = new Song("S1003", "Something Just Like This","The Chainsmokers","499eefd42a24ec562c464bd7acfad7ed41eb9179?cid=2afe87a64b0042dabf51f37318616965", 4.13, "something_just_like_this");
Song southOfTheBorder = new Song("S1004", "South of the Border","Ed Sheeran","7b43dd0c94b0af0c0401381a683d2f4833180ba3?cid=2afe87a64b0042dabf51f37318616965", 3.41, "south_of_the_border");
Song oldTownRoad = new Song("S1005", "Old Town Road","Lil Nas X","3bc62106123fcafad475271e72e74cd7f519ab83?cid=2afe87a64b0042dabf51f37318616965", 1.9, "old_town_road");
Song noGuidance = new Song("S1006", "No Guidance", "Chris Brown", "7c3bc7b4d1741a001463b570fe29f922d9c42bd6?cid=2afe87a64b0042dabf51f37318616965", 4.34, "no_guidance");
Song closer = new Song("S1007", "Closer", "The Chainsmokers", "8d3df1c64907cb183bff5a127b1525b530992afb?cid=2afe87a64b0042dabf51f37318616965", 4.08, "closer");
Song sideface = new Song("S1008", "側臉", "于果", "c8cc891a7cacb36857ea15c8fcfc4da6e4b1583d?cid=2afe87a64b0042dabf51f37318616965", 3.63, "sideface");
Song kebukeyi = new Song("S1009", "可不可以", "张紫豪", "2d790215acf7c4e6c5e093255b94a936064f75ed?cid=2afe87a64b0042dabf51f37318616965", 4.01, "kebukeyi");
allSongs[0]= theWayYouLookTonight;
allSongs[1]= billiejean;
allSongs[2]= somethingJustLikeThis;
allSongs[3]= southOfTheBorder;
allSongs[4]= oldTownRoad;
allSongs[5]= noGuidance;
allSongs[6]= closer;
allSongs[7]= sideface;
allSongs[8]= kebukeyi;
}
public Song searchById (String id){
Song selectedSong = null;
for(int index=0; index<allSongs.length; index++){
selectedSong = allSongs[index];
if(selectedSong.getId().equals(id)){
return selectedSong;
}
}
return selectedSong;
}
//create a method to retrieve the next song
public Song getNextSong(String currentSongId){
Song nextSong = null;
for(int x = 0; x < allSongs.length; x++){
String tempSongId = allSongs[x].getId();
if(tempSongId.equals(currentSongId) && (x < allSongs.length -1)){
nextSong = allSongs[x+1];
break;
}
}
return nextSong;
}
//create a method to retrieve the previous song
public Song getPrevSong(String currentSongId){
Song PrevSong = null;
for(int x = 0; x < allSongs.length; x++){
String tempSongId = allSongs[x].getId();
if(tempSongId.equals(currentSongId) && (x > 0)){
PrevSong = allSongs[x-1];
break;
}
}
return PrevSong;
}
//create a method to get random song
public Song getRandomSong(){
Song randomSong = null;
int max = 2;
int min = 0;
int randomNum = (int)(Math.random()*4);
randomSong = allSongs[randomNum];
return randomSong;
}
}
Song.class codes
package com.example.musix;
public class Song {
//private attributes are hidden from other classes/files
private String id;
private String title;
private String artiste;
private String fileLink;
private double songLength;
private String coverArt;
public Song(String _id, String _title, String _artiste, String _fileLink, double _songLength, String _coverArt){
this.id = _id;
this.title = _title;
this.artiste = _artiste;
this.fileLink = _fileLink;
this.songLength = _songLength;
this.coverArt = _coverArt;
}
//encapsulation
//SET methods for setting/changing of the values of the attributes
public void setId(String id) {
this.id = id;
}
public void setTitle(String title) {
this.title = title;
}
public void setArtiste(String artiste) {
this.artiste = artiste;
}
public void setFileLink(String fileLink) {
this.fileLink = fileLink;
}
public void setSongLength(double songLength) {
this.songLength = songLength;
}
public void setCoverArt(String coverArt) {
this.coverArt = coverArt;
}
//GET methods allows us to retrieve values of the attributes
public String getId() {
return this.id;
}
public String getTitle() {
return this.title;
}
public String getArtiste() {
return this.artiste;
}
public String getFileLink() {
return this.fileLink;
}
public double getSongLength() {
return this.songLength;
}
public String getCoverArt() {
return this.coverArt;
}
}
codes for getResourceId
public final class AppUtil
{
public static void popMessage(Context context, String message)
{
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
public static String getResourceId(Context context, View view)
{
String id = context.getResources().getResourceEntryName(view.getId());
return id;
}
String resourceId = AppUtil.getResourceId(SearchSong.this, myList);
Song selectedSong = mySongCollection.searchById(resourceId);
resourceId is going to be the id of the element of the list view (eg. first element id = 0, 2nd id = 1 and so on).
public Song searchById (String id){
Song selectedSong = null;
for(int index=0; index<allSongs.length; index++){
selectedSong = allSongs[index];
if(selectedSong.getId().equals(id)){
return selectedSong;
}
}
return selectedSong;
}
Should be:
public Song searchById (String id){
//we are returning the song selected by the index of its Arrays
Song selectedSong = allSongs[Integer.parseInt(id)];
return selectedSong;
}
Why?:
Your returning the actual songid, but in
Song selectedSong = mySongCollection.searchById(resourceId); <-- resourceId is already the Id stored in the database and not the index of mySongCollection.
intent.putExtra("id", selectedSong.getId());
you are using already the actuals song id. This doesen't make sense as you can already identify the actual song.
So either apply these changes or change this line:
intent.putExtra("id", resourceId);
I'm using ListView to showing the data retrieved from my database, it suppose work before, but it suddenly doesn't and show things. Normally it should showing things like this (Screenshot from other project):
Edited, post my all code:
public class MainActivity extends AppCompatActivity {
private TextView mTextMessage;
String[] dataDetail;
ArrayList<dataDetail> allDetail = new ArrayList<>();
ListView detailList;
final Context context = this;
final int min = 0;
final int max = 10;
final int random = new Random().nextInt((max - min) + 1) + min;
int score = 0;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
mTextMessage.setText(R.string.title_home);
return true;
case R.id.navigation_dashboard:
mTextMessage.setText(R.string.title_dashboard);
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
detailList = findViewById(R.id.dataView);
mTextMessage = (TextView) findViewById(R.id.message);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
new GetData().execute();
}
private class GetData extends AsyncTask<Void, Void, ArrayList<dataDetail>> {
protected ArrayList<dataDetail> doInBackground(Void... voids) {
HttpURLConnection urlConnection;
InputStream in = null;
try {
URL url = new URL("http://10.0.2.2:8080/projectServer/DataDetailDB?getdata=true");
urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedInputStream(urlConnection.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
String response = convertStreamToString(in);
System.out.println("Server response = " + response);
try {
JSONArray jsonArray = new JSONArray(response);
dataDetail = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
final String customerName = jsonArray.getJSONObject(i).get("customerName").toString();
final String carName = jsonArray.getJSONObject(i).get("carName").toString();
final String appointmentDate = jsonArray.getJSONObject(i).get("appointmentDate").toString();
final String email = jsonArray.getJSONObject(i).get("email").toString();
final String issueDescribe = jsonArray.getJSONObject(i).get("issueDescribe").toString();
final String timeForJob = jsonArray.getJSONObject(i).get("timeForJob").toString();
final String costForJob = jsonArray.getJSONObject(i).get("costForJob").toString();
final String reliableOnCar = jsonArray.getJSONObject(i).get("reliableOnCar").toString();
final String distanceJob = jsonArray.getJSONObject(i).get("distance").toString();
final int finalScore = score;
if (random * Float.parseFloat(timeForJob) < 15) {
score += 1;
} if (random * Float.parseFloat(reliableOnCar) > 15) {
score += 1;
} if (random * Float.parseFloat(distanceJob) > 10) {
score -=1;
} if (random * Float.parseFloat(costForJob) > 40) {
score -=1;
} if(random * Float.parseFloat(timeForJob) + random * Float.parseFloat(reliableOnCar) +
random * Float.parseFloat(distanceJob) + random * Float.parseFloat(costForJob) > 500) {
score += 5;
} else {
score += 0;
}
dataDetail tData = new dataDetail(customerName, carName, appointmentDate, email, issueDescribe, timeForJob, costForJob, reliableOnCar, distanceJob, finalScore);
allDetail.add(tData);
System.out.println("customername = " + customerName + ", Score = " + finalScore);
if (score >= 5) {
dataDetail[i] = "Name: " + customerName + "\n" + "Appointment Date: " + appointmentDate + "\n" + "Urgent";
} else if (score >= 3) {
dataDetail[i] = "Name: " + customerName + "\n" + "Appointment Date: " + appointmentDate + "\n" + "Second urgent";
} else {
dataDetail[i] = "Name: " + customerName + "\n" + "Appointment Date: " + appointmentDate + "\n" + "Normal";
}
System.out.print("Debug: " + dataDetail);
Collections.sort(allDetail, new Comparator<advprog.mmu.ac.uk.schedulerapp.dataDetail>() {
#Override
public int compare(dataDetail o1, dataDetail o2) {
return Integer.compare(o1.getFinalScore(), o2.getFinalScore());
}
});
Collections.reverse(allDetail);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(ArrayList<dataDetail> dataDetailArrayList) {
super.onPostExecute(dataDetailArrayList);
ArrayAdapter List = new ArrayAdapter(context, android.R.layout.simple_list_item_1, allDetail);
detailList.setAdapter(List);
}
}
public String convertStreamToString(InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}}
dataDetial Class:
public class dataDetail {
private String customerName;
private String carName;
private String appointmentDate;
private String email;
private String issueDescribe;
private String timeForJob;
private String costForJob;
private String reliableOnCar;
private String distanceJob;
private int finalScore;
public dataDetail(String customerName, String carName, String appointmentDate, String email, String issueDescribe, String timeForJob, String costForJob, String reliableOnCar, String distanceJob, int finalScore) {
this.customerName = customerName;
this.carName = carName;
this.appointmentDate = appointmentDate;
this.email = email;
this.issueDescribe = issueDescribe;
this.timeForJob = timeForJob;
this.costForJob = costForJob;
this.reliableOnCar = reliableOnCar;
this.distanceJob = distanceJob;
this.finalScore = finalScore;
}
public int getFinalScore() {
return finalScore;
}
public void setFinalScore(int finalScore) {
this.finalScore = finalScore;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCarName() {
return carName;
}
public void setCarName(String carName) {
this.carName = carName;
}
public String getAppointmentDate() {
return appointmentDate;
}
public void setAppointmentDate(String appointmentDate) {
this.appointmentDate = appointmentDate;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getIssueDescribe() {
return issueDescribe;
}
public void setIssueDescribe(String issueDescribe) {
this.issueDescribe = issueDescribe;
}
public String getTimeForJob() {
return timeForJob;
}
public void setTimeForJob(String timeForJob) {
this.timeForJob = timeForJob;
}
public String getCostForJob() {
return costForJob;
}
public void setCostForJob(String costForJob) {
this.costForJob = costForJob;
}
public String getReliableOnCar() {
return reliableOnCar;
}
public void setReliableOnCar(String reliableOnCar) {
this.reliableOnCar = reliableOnCar;
}
public String getDistanceJob() {
return distanceJob;
}
public void setDistanceJob(String distanceJob) {
this.distanceJob = distanceJob;
} }
I think this line dataDetail[i] = "Name: " + customerName + "\n" + "Appointment Date: " + appointmentDate + "\n" + "Urgent"; will be showing the data I want to show in the ListView, but it shows the data like this:
And when I trying to print out the dataDetail, in logcat it gives me this:
I/System.out: customername = Josh, Score = 0
Debug: [Ljava.lang.String;#e883626customername = Wolski, Score = 1
I/System.out: Debug: [Ljava.lang.String;#e883626customername = Cardinal, Score = 2
I/System.out: Debug: [Ljava.lang.String;#e883626customername = Pang, Score = 3
Since you are using the default ArrayAdapter you are rendering the toString() of your dataDetail class. You have at least the following choices:
Define a custom toString() in dataDetail to present the information that you need. Something like:
#Override
public String toString() {
return "Name: " + carName;
}
In order to present the car names.
Define and use a custom adapter where you can use a custom view holder to render the desired data. See here for more details if you are using a RecyclerView.
You can also extend the ArrayAdapter too. See this answer for more details.
I would recommend using a RecyclerView with a custom adapter, instead of the ListView, one similar to what is presented here. This way you gain a lot of flexibility and your app will be able to present a lot of elements in an efficient way. See here a good comparison between the two.
dataDetail tData = new dataDetail(customerName, carName, appointmentDate, email, issueDescribe, timeForJob, costForJob, reliableOnCar, distanceJob, finalScore);
allDetail.add(tData.getCustomerName());
arrya adapter use only string type array list so it put tdata as string in allDetails
The project im working on allow the user to register and login and all works perfectly until I spotted something wrong with the code. It doesn't count as an error because the compiler don't think its an error. Its just a bug or whatever people call it is. So here's what happened . The user login to their account, the database transfer their data into intent extras. then on the next activities, the username, coins and gems appears on top of the page so that the user know how much coins they have left. For testing purpose, i added add coin and decrease coin button. still, the code works perfectly. But after the user log out and relogin, the coins backs to the original amount. I know the problem caused by putting a value on the coin variable in User.java class. And still while logging in I put the default value of coins and gems for the user in the intent extras. I just cant find my way on how to put the value from database to the intent extras while user logging in.
so heres the code for login activity
buttonLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Check user input is correct or not
if (validate()) {
//Get values from EditText fields
String Email = editTextEmail.getText().toString();
String Password = editTextPassword.getText().toString();
User player1 = new User(null, null, Email, Password);
//Authenticate user
User currentUser = myDb.Authenticate(player1);
//Check Authentication is successful or not
if (currentUser != null) {
System.out.println("Success");
Bundle extras = new Bundle();
extras.putString("P_ID", currentUser.getId());
extras.putString("P_NAME", currentUser.getName());
extras.putInt("P_COINS", currentUser.getCoins());
extras.putInt("P_GEMS", currentUser.getGems());
Intent intent = new Intent(getApplicationContext(),HomeActivity.class);
intent.putExtras(extras);
startActivity(intent);
finish();
} else {
//User Logged in Failed
System.out.println("Failed");
}
}
}
});
the homeactivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set fullscreen and no title//////////
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
///////////////////////////////////////
setContentView(R.layout.home_screen);
myDb = new DatabaseHelper(this);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
pid = extras.getString("P_ID");
pname = extras.getString("P_NAME");
pcoins = extras.getInt("P_COINS");
pgems = extras.getInt("P_GEMS");
nametxt = (TextView)findViewById(R.id.playernametext);
coinstxt = (TextView)findViewById(R.id.playercoinstext);
gemstxt = (TextView)findViewById(R.id.playergemstext);
addcoin = (Button)findViewById(R.id.addbtn);
decoin = (Button)findViewById(R.id.decbtn);
nametxt.setText(" " +String.valueOf(pname) +" ");
coinstxt.setText(" Coins : " +String.valueOf(pcoins) +" ");
gemstxt.setText(" Gems : " +String.valueOf(pgems) +" ");
addcoin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pcoins += 10;
boolean isUpdate = myDb.updateUser(pid, pname, String.valueOf(pcoins), String.valueOf(pgems));
if (isUpdate == true) {
nametxt.setText(" " +String.valueOf(pname) +" ");
coinstxt.setText(" Coins : " +String.valueOf(pcoins) +" ");
gemstxt.setText(" Gems : " +String.valueOf(pgems) +" ");
}
}
});
decoin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pcoins -= 10;
boolean isUpdate = myDb.updateUser(pid, pname, String.valueOf(pcoins), String.valueOf(pgems));
if (isUpdate == true) {
nametxt.setText(" " +String.valueOf(pname) +" ");
coinstxt.setText(" Coins : " +String.valueOf(pcoins) +" ");
gemstxt.setText(" Gems : " +String.valueOf(pgems) +" ");
}
}
});
}
and of course the user class
public class User {
public String id;
public String userName;
public String email;
public String password;
public int coins = 1000;
public int gems = 10;
public User(String id, String userName, String email, String password) {
this.id = id;
this.userName = userName;
this.email = email;
this.password = password;
}
public String getId() {
return this.id;
}
public String getName() {
return this.userName;
}
public void addCoins(int addAmount) {
this.coins = addAmount;
}
public void decCoins(int decAmount) {
this.coins = decAmount;
}
public int getCoins() {
return this.coins;
}
public void addGems(int addAmount) {
this.gems = addAmount;
}
public void decGems(int decAmount) {
this.gems = decAmount;
}
public int getGems() {
return this.gems;
}
}
Honestly, my brain lacks of logic. Thats why i come here, to see whether my code does make sense.
And please, if you don't understand what i mean, just ask me which parts and please just dont immediately flag my question. Im really bad at english, trust me.
I'd suggest only passing the userid (which should never change) and then always getting the values coins etc from the database and also only changing them in the database (followed by resetting the displayed values from the values in the database).
You would then not have the issue of trying to juggle two sets of data you would then rely on the real data i.e. that in the database.
Working Example
The following is some code that goes through the basics.
When it starts the MainActivity, immediately starts the LoginActivity when you login then it takes you to the HomeActivity. This display the current Userid, Username, coins (initially 0) and gems.
There are 2 buttons Add10Coins and Add10gems clicking them will apply the new values to the DB displaying the updated values. If you stop the App and rerun, login then the values will be as they were.
Passing values wise, although the LoginActivity sets 3 Intent Extra values only one is used (the userid as a long) by the HomeActivity, but as per the values display all are accessible. If another activity is started then all you have to do is pass the userid via the intent.
The code isn't what I'd call complex but I'd certainly suggest going through it and try to understand it.
user.java
I've added some methods and also added some Constants, this is now :-
public class User {
public static final int ADJUSTTYPE_ADD = 1;
public static final int ADJUSTTYPE_REPLACE = 2;
public static final int ADJUSTTYPE_MULTIPLY = 3;
public static final int ADJUSTTYPE_DIVIDE = 4;
String id;
String userName;
String email;
String password;
int coins;
int gems;
public User(String id, String userName, String email, String password) {
this.id = id;
this.email = email;
//And so on. Don't mind this
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setName(String userName) {
this.userName = userName;
}
public String getName() {
return this.userName;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword() {
return password;
}
public void setCoins(int coins) {
this.coins = coins;
}
public int getCoins() {
return this.coins;
}
public void setGems(int gems) {
this.gems = gems;
}
public int getGems() {
return this.gems;
}
public long getLongId() {
long id;
try {
id = Long.valueOf(this.id);
} catch (Exception e) {
return -1;
}
return id;
}
}
DatabaseHelper.java
This has been written from scratch based upon not the most stringent inspection of your code, it will largely be affected by my styling/usage techniques but not to the extent that I'd apply for real development.
Within this is the method adjustCoinsAndOrGems this is what is used to update the gems or coins in the DB and also in the returned User (so that a synchronised version of the User is returned, not that this returned use is used (I personally prefer to access the database as long as it's not an issue (e.g. noticeably affects performance)))
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DBNAME = "mygame.db";
public static final int DBVERSION = 1;
public static final String TBL_USER = "user";
public static final String COL_USER_ID = BaseColumns._ID;
public static final String COL_USER_NAME = "user_name";
public static final String COL_USER_EMAIL = "user_email";
public static final String COL_USER_PASWWORD = "user_password";
public static final String COL_USER_COINS = "user_coins";
public static final String COL_USER_GEMS = "user_gems";
public static final String TBL_PLAYER = "player";
public static final String COL_PLYAER_ID = BaseColumns._ID;
public static final String COL_PLAYER_OWNINGUSER = "player_owninguser";
public static final String COL_PLAYER_NAME = "player_name";
//...... other columns
SQLiteDatabase mDB;
public DatabaseHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
mDB = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
String crt_tbl_user = "CREATE TABLE IF NOT EXISTS " + TBL_USER + "(" +
COL_USER_ID + " INTEGER PRIMARY KEY," +
COL_USER_NAME + " TEXT NOT NULL UNIQUE," +
COL_USER_EMAIL + " TEXT NOT NULL UNIQUE," +
COL_USER_PASWWORD + " TEXT NOT NULL," +
COL_USER_COINS + " INTEGER," +
COL_USER_GEMS + " INTEGER" +
")";
String crt_tbl_player = "CREATE TABLE IF NOT EXISTS " + TBL_PLAYER + "(" +
COL_PLYAER_ID + " INTEGER PRIMARY KEY," +
COL_PLAYER_NAME + " TEXT NOT NULL," +
COL_PLAYER_OWNINGUSER + " INTEGER REFERENCES " + TBL_USER + "(" + COL_USER_ID + ")" +
")";
db.execSQL(crt_tbl_user);
db.execSQL(crt_tbl_player);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
/*
Note core add but not intended to be used directly
Note this assumes that checks are done to ensure that name, email and password
have been provided
*/
private long addUser(Long id, String name, String email, String password, int coins, int gems) {
ContentValues cv = new ContentValues();
if (id > 0) {
cv.put(COL_USER_ID,id);
}
if (name.length() > 0) {
cv.put(COL_USER_NAME,name);
}
if (email.length() > 0 ) {
cv.put(COL_USER_EMAIL,email);
}
if (password.length() > 0) {
cv.put(COL_USER_PASWWORD,password);
}
cv.put(COL_USER_COINS,coins);
cv.put(COL_USER_GEMS,gems);
if (cv.size() < 1) return -1; //<<<<<<<<<< return if nothing to add
return mDB.insert(TBL_USER,null,cv);
}
/*
For add with just name, email and password (normal usage)
*/
public long addUser(String name, String email, String password) {
return this.addUser(-1L,name,email,password,0,0);
}
/*
For adding a user setting the coins and gems (special usage)
*/
public long addUserSettingCoinsAndGems(String name, String email, String password, int coins, int gems) {
return this.addUser(-1L,name,email,password,coins,gems);
}
public User getUser(long id) {
User rv = new User("-1","",",",""); // Invalid user
String whereclause = COL_USER_ID + "=?";
String[] whereargs = new String[]{String.valueOf(id)};
Cursor csr = mDB.query(TBL_USER,null,whereclause,whereargs,null,null,null);
if (csr.moveToFirst()) {
rv.setId(String.valueOf(id));
rv.setName(csr.getString(csr.getColumnIndex(COL_USER_NAME)));
rv.setEmail(csr.getString(csr.getColumnIndex(COL_USER_EMAIL)));
rv.setPassword(csr.getString(csr.getColumnIndex(COL_USER_PASWWORD)));
rv.setCoins(csr.getInt(csr.getColumnIndex(COL_USER_COINS)));
rv.setGems(csr.getInt(csr.getColumnIndex(COL_USER_GEMS)));
}
csr.close();
return rv;
}
public User getUser(String userid) {
String whereclause = COL_USER_ID + "=?";
User rv = new User("-1","",",",""); // Invalid user
long id;
try {
id = Long.valueOf(userid);
} catch (Exception e) {
return rv;
}
String[] whereargs = new String[]{String.valueOf(id)};
Cursor csr = mDB.query(TBL_USER,null,whereclause,whereargs,null,null,null);
if (csr.moveToFirst()) {
rv.setId(String.valueOf(id));
rv.setName(csr.getString(csr.getColumnIndex(COL_USER_NAME)));
rv.setEmail(csr.getString(csr.getColumnIndex(COL_USER_EMAIL)));
rv.setPassword(csr.getString(csr.getColumnIndex(COL_USER_PASWWORD)));
rv.setCoins(csr.getInt(csr.getColumnIndex(COL_USER_COINS)));
rv.setGems(csr.getInt(csr.getColumnIndex(COL_USER_GEMS)));
}
csr.close();
return rv;
}
public User getUser(String email, String password) {
User rv = new User("-1","","","");
String whereclause = COL_USER_EMAIL + "=? AND " + COL_USER_PASWWORD + "=?";
String[] whereargs = new String[]{email,password};
Cursor csr = mDB.query(TBL_USER,null,whereclause,whereargs,null,null,null);
if (csr.moveToFirst()) {
rv.setId( String.valueOf(csr.getLong(csr.getColumnIndex(COL_USER_ID))));
rv.setName(csr.getString(csr.getColumnIndex(COL_USER_NAME)));
rv.setEmail(csr.getString(csr.getColumnIndex(COL_USER_EMAIL)));
rv.setPassword(csr.getString(csr.getColumnIndex(COL_USER_PASWWORD)));
rv.setCoins(csr.getInt(csr.getColumnIndex(COL_USER_COINS)));
rv.setGems(csr.getInt(csr.getColumnIndex(COL_USER_GEMS)));
}
csr.close();
return rv;
}
public User adjustCoinsAndOrGems(User u, int coins, int coin_adjustmode, int gems, int gem_adjustmode) {
ContentValues cv = new ContentValues();
User rv;
User user_fromDB = getUser(u.getId());
if (user_fromDB.id.equals("-1")) return u; // User not found so return
switch (coin_adjustmode) {
case User.ADJUSTTYPE_REPLACE:
cv.put(COL_USER_COINS,coins);
break;
case User.ADJUSTTYPE_ADD:
if (coins != 0) {
cv.put(COL_USER_COINS,user_fromDB.getCoins() + coins);
}
break;
case User.ADJUSTTYPE_MULTIPLY:
if (coins > 0) {
cv.put(COL_USER_COINS,user_fromDB.getCoins() * coins);
}
break;
case User.ADJUSTTYPE_DIVIDE:
if (coins > 0) {
cv.put(COL_USER_COINS,user_fromDB.getCoins() / coins);
}
break;
}
switch (gem_adjustmode) {
case User.ADJUSTTYPE_REPLACE:
cv.put(COL_USER_GEMS,gems);
break;
case User.ADJUSTTYPE_ADD:
if (gems != 0) {
cv.put(COL_USER_GEMS,user_fromDB.getGems() + gems);
}
break;
case User.ADJUSTTYPE_MULTIPLY:
if (gems > 0) {
cv.put(COL_USER_GEMS,user_fromDB.getGems() * gems);
}
break;
case User.ADJUSTTYPE_DIVIDE:
if (gems > 0) {
cv.put(COL_USER_GEMS,user_fromDB.getGems() / gems);
}
break;
}
if (cv.size() < 1) return u;
String whereclause = COL_USER_ID + "=?";
String[] whereargs = new String[]{u.getId()};
mDB.update(TBL_USER,cv,whereclause,whereargs);
return getUser(user_fromDB.getId());
}
public boolean authenticateUser(String email, String password) {
User u = getUser(email,password);
return (u.getLongId() > 0);
}
}
MainActivity.java
Very simple activity that starts the LoginActivity and when finally returned to does nothing (so you might as well kill the app).
public class MainActivity extends AppCompatActivity {
TextView mMessage;
DatabaseHelper mDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMessage = this.findViewById(R.id.message);
mDB = new DatabaseHelper(this);
addSomeTestingUsers();
// Immediately start Login Activity
Intent i = new Intent(MainActivity.this,LoginActivity.class);
startActivity(i);
}
#Override
protected void onResume() {
super.onResume();
mMessage.setText("Welcome back");
}
private void addSomeTestingUsers() {
if (DatabaseUtils.queryNumEntries(mDB.getWritableDatabase(),DatabaseHelper.TBL_USER) > 0) return;
mDB.addUser("Fred","fred#fredmal.com","password");
mDB.addUser("Mary","mary#mary.email.com","password");
}
}
LoginActivity
This is pretty straightforward note that as it stands you have to Login and that the emails and passwords for the 2 users are coded in the MainActivity. When supplied correctly the HomeActivivty is started :-
public class LoginActivity extends AppCompatActivity {
public static final String INTENTKEY_USERNAME = "IK_USERNAME";
public static final String INTENTKEY_USERID = "IK_USERID";
public static final String INTENTKEY_STRINGUSERID = "IK_USERIDSTRING";
Button mloginbtn;
EditText mEmail,mPassword;
Context mContext;
DatabaseHelper mDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mContext = this;
mloginbtn = this.findViewById(R.id.loginbtn);
mEmail = this.findViewById(R.id.email);
mPassword = this.findViewById(R.id.password);
mDB = new DatabaseHelper(this);
mloginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
handleAuthentication();
}
});
}
private void handleAuthentication() {
if (mDB.authenticateUser(mEmail.getText().toString(),mPassword.getText().toString())) {
User u = mDB.getUser(mEmail.getText().toString(),mPassword.getText().toString());
Intent i = new Intent(mContext,HomeActivity.class);
i.putExtra(INTENTKEY_USERNAME,u.getName());
i.putExtra(INTENTKEY_USERID,u.getLongId());
i.putExtra(INTENTKEY_STRINGUSERID,u.getId());
startActivity(i);
finish();
}
}
HomeActivity
For brevity, this has been used to display the coins and gems, it to is pretty basic and relies upon methods in the DatabaseHelper to do much of the work.
public class HomeActivity extends AppCompatActivity {
TextView mUserameTextView, mUseridTextView, mCoinsTextView, mGemsTextView;
Button mAdd10Coins, mAdd10Gems,mDone;
User mUser;
long mUserid;
Context mContext;
DatabaseHelper mDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mContext = this;
mDB = new DatabaseHelper(mContext);
mUserameTextView = this.findViewById(R.id.username);
mUseridTextView = this.findViewById(R.id.userid);
mCoinsTextView = this.findViewById(R.id.coins);
mGemsTextView = this.findViewById(R.id.gems);
Intent i = this.getIntent();
mUserid = i.getLongExtra(LoginActivity.INTENTKEY_USERID,-1);
mUser = mDB.getUser(mUserid);
refreshDisplay();
initButtons();
}
private void initButtons() {
mAdd10Coins = this.findViewById(R.id.add10coins);
mAdd10Coins.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDB.adjustCoinsAndOrGems(mUser,10,User.ADJUSTTYPE_ADD,0,User.ADJUSTTYPE_ADD);
mUser = mDB.getUser(mUserid);
refreshDisplay();
}
});
mAdd10Gems = this.findViewById(R.id.add10gems);
mAdd10Gems.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDB.adjustCoinsAndOrGems(mUser,0, User.ADJUSTTYPE_ADD,10,User.ADJUSTTYPE_ADD);
mUser = mDB.getUser(mUserid);
refreshDisplay();
}
});
mDone = this.findViewById(R.id.done);
mDB = new DatabaseHelper(mContext);
mDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
private void refreshDisplay() {
mUseridTextView.setText(mUser.getId());
mUserameTextView.setText(mUser.getName());
mCoinsTextView.setText(String.valueOf(mUser.getCoins()));
mGemsTextView.setText(String.valueOf(mUser.getGems()));
}
}
I'm doing create an Catalogue Movie app. I have a ListView which contains an ImageView, title, description, and release date.
In the ListView, I take a substring of the description, because it's too long if showed in a ListView, and now I want to get the real description, in the DetailActivity (setOnItemClickListener).
This is my code:
try {
String title = object.getString("title");
String description = object.getString("overview");
double movieRatet = object.getDouble("vote_average");
String movieRate = new DecimalFormat("#.#").format(movieRatet);
String releaseDate = object.getString("release_date");
String posterUrl = object.getString("poster_path");
posterUrl = POSTER_BASE_URL + "w185" + posterUrl;
description = description.length() > 64 ? description.substring(0,64)+"...":description;
Log.d("movie poster", posterUrl);
Log.d("movie title ", title);
Log.d("movie description ", description);
Log.d("movie release ", releaseDate);
this.title = title;
this.description = description;
this.rate = releaseDate;
this.imgurl = posterUrl;
}catch (Exception e){
e.printStackTrace();
}
This is my OnItemClickListener:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "Clicked"+position,Toast.LENGTH_LONG).show();
RelativeLayout listItem = (RelativeLayout) view.findViewById(R.id.rl_item);
TextView clickedItemView = (TextView) listItem.findViewById(R.id.tv_judul);
TextView clickedItemView2 = (TextView) listItem.findViewById(R.id.tv_deskripsi);
TextView clickedItemView3 = (TextView) listItem.findViewById(R.id.tv_rate);
String title = clickedItemView.getText().toString();
String desk = clickedItemView2.getText().toString();
String rate = clickedItemView3.getText().toString();
Intent i = new Intent(getApplicationContext(), DetailActivity.class);
desk.substring(0);
i.putExtra("title", title);
i.putExtra("desk", desk);
i.putExtra("rate", rate);
startActivity(i);
}
});
Picture of the DetailActivity:
I want to get the full description, how?
you can add a params "fullMessage" to storage the all of the message,and "description" to storage some message.Then use i.putExtra("desk", fullMessage) to carry full message to another activity.
Another solution is to add those attribute to your TextView in ListView
<TextView
<!-- other value -->
android:maxLines="3"
android:ellipsize="end"/>
And you can put full message to this TextView,it will folding itself when the message is too long.
Just do not overwrite your description variable. Instead of above have one more variable that holds your truncated value, say overview.
String overview = description.length() > 64 ? description.substring(0,64)+"...":description;
Then your description variable will continue to hold the original value. Just use that where you need.
Try this :
mymodalclass:make class
public class MyModal {
String title ;
String description ;
double movieRatet ;
String movieRate;
String releaseDate;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public double getMovieRatet() {
return movieRatet;
}
public void setMovieRatet(double movieRatet) {
this.movieRatet = movieRatet;
}
public String getMovieRate() {
return movieRate;
}
public void setMovieRate(String movieRate) {
this.movieRate = movieRate;
}
public String getReleaseDate() {
return releaseDate;
}
public void setReleaseDate(String releaseDate) {
this.releaseDate = releaseDate;
}
public String getPosterUrl() {
return posterUrl;
}
public void setPosterUrl(String posterUrl) {
this.posterUrl = posterUrl;
}
String posterUrl ;
}
//****************************************
while parsing data :
Arraylist list = new ArrayList();
for(int i=0;i<yourjsonarray.length();i++){
JSONObject object = yourjsonarray.getJSONObject(i);
MyModal m = new MyModal();
m.setTitle(object.getString("title"));//like this set all data
//now add this object to list
list.add(m);
}
//now when you click list just get clicked position and by this position get that particular object and pass that to next activity
ex: position = your_clicked_position
MyModal clicked_modal_object = (MyModal) list.get(your_clicked_position);
//now pass this clicked_modal_object to next activity
You can use two variables.(I'm sure this is what #Gautam mentioned) The first is the full description and the second is the shorter description.
String description = object.getString("overview"); // full
String shortDesc = description.length() > 64 ? description.substring(0,64)+"...":description; // add this to listView
Log.d("movie description ", shortDesc);
I want to get the real description, in the DetailActivity
(setOnItemClickListener)
When button clicked, get the description string instead
i.putExtra("desk", description);
Note: Make sure you set description as globally.
I have a ListView which is display several String when i click on a categories it will call and pop out a dialog options menu which has the options of English, Hindi and Cancel. The onClicklistener will be triggered when the user Click one of the category from the Listview such as "Novel", "Book" or "Plays".
What I want to do here is, when the user clicks "Book" and choose language English option, I want to pass category_id and language_id to the next activity.the category_id and language_id are the json object that i got from the server response. So I need to get the category_id selected from listview and pass it to the next activity along with the language_id as seleceted in dialog box.
if this is possible then how? Thanks in advance for your help.
holder.imageView.setImageUrl(Config.TAG_IMAGE_URL+category.getImage(), imageLoader);
holder.textViewName.setText(category.getName());
category_id = category.getId();
language_id = category.getLanguage_id();
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
handleLanguageDialog();
}
});
}
private AlertDialog handleLanguageDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Select Language")
.setItems(R.array.lang, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
switch(which)
{
case 0:// English
break;
case 1://Bengali
break;
}
}
});
return builder.create().show();
}
categ.java
private String id;
private String name;
private String description;
private String image;
private String parent_id;
private String language_id;
private String created;
private String modified;
#Override
public String toString() {
return "Categ{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", description='" + description + '\'' +
", image='" + image + '\'' +
", parent_id='" + parent_id + '\'' +
", language_id='" + language_id + '\'' +
", created='" + created + '\'' +
", modified='" + modified + '\'' +
'}';
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getParent_id() {
return parent_id;
}
public void setParent_id(String parent_id) {
this.parent_id = parent_id;
}
public String getLanguage_id() {
return language_id;
}
public void setLanguage_id(String language_id) {
this.language_id = language_id;
}
public String getCreated() {
return created;
}
public void setCreated(String created) {
this.created = created;
}
public String getModified() {
return modified;
}
public void setModified(String modified) {
this.modified = modified;
}
}
In your first activity pass data like this
Intent intent = new Intent(this, NextActivity.class);
intent.putExtra("CATEGORY_ID", category_id);
intent.putExtra("LANGUAGE_ID", language_id);
startActivity(intent);
Now in your next activity recieve data like this
String cat_id = getIntent().getExtras().getString("CATEGORY_ID");
String cat_id = getIntent().getExtras().getString("LANGUAGE_ID");
Pass like this inside your switch case
case 0:
Intent intent = new Intent(YourCurrentActivity.this, Destination.class);
intent.putExtra("category_key", category_id);
intent.putExtra("language_key", language_id);
startActivity(intent);
Intent intent = new Intent(SourceActivity.this,destinationAvtivity.java);
intent.putExtra("category_id",109);
startActivity(theintent);