local image through json in android - java

SO i have json file which contain this code :
{
"gejala": "Apakah hawar berwarna kuning terang menuju ujung daun",
"gejala_kode": "GJL0025",
"penyakit_kode": "PNY0012",
"gambar_gejala":"hawar_daun",
"child": null
}
hawar_daun is name of the image i put on my drawable folder.
my xml part :
<RelativeLayout
android:id="#+id/big_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textView4"
android:background="#drawable/bubble1"
android:layout_marginTop="20dip">
<TextView
android:layout_width="match_parent"
android:layout_height="200dp"
android:text="null"
android:textSize="17dp"
android:id="#+id/ask"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:id="#+id/gambargejala"
/>
</RelativeLayout>
and this is part of my java code which i want to put the image.
public class KonsultasiBerdasarkanGejalaActivity extends AppCompatActivity {
public static final String ASK_GEJALA = "Apakah terdapat tanda-tanda ini?" ;
int qIndex = 0;
int level = 0;
TextView header;
TextView ask;
ImageView askgambar;
Button ya;
Button tidak;
ScrollView lyContainer;
boolean calculate = false;
boolean fromTidak = false;
int calcCount = 0;
int yaCount = 0;
int tidakCount = 0;
boolean lastQuestion = false;
PohonKeputusan pohonKeputusan;
Padi padi;
String[] gejalaPadi;
ArrayList<PenyakitPadi> allPenyakit;
ArrayList<PenyakitPadi> relPenyakitPadiArr;
ArrayList<PohonKeputusan> pohonKeputusanObjArr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_konsultasi_start);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
setTitle(" Menu Konsultasi");
toolbar.setSubtitle(" Berdasarkan Gejala");
lyContainer = (ScrollView) findViewById(R.id.lyContainer);
Intent padiIntent = getIntent();
padi = padiIntent.getExtras().getParcelable("padiObj");
gejalaPadi = padi.gejala;
relPenyakitPadiArr = setRelatedPenyakit();
try {
pohonKeputusanObjArr = setRelatedGejala(initiatePohonKeputusan());
Log.e("pohonKeputusanObjArr", String.valueOf(pohonKeputusanObjArr.size()));
Log.e("pohonKeputusanObjArr", String.valueOf(pohonKeputusanObjArr.toString()));
} catch (IOException e) {
e.printStackTrace();
}
pohonKeputusan = pohonKeputusanObjArr.get(qIndex);
//Log.e("pohonKeputusan", String.valueOf(pohonKeputusan.gejala_kode));
String namaPadi = padi.nama;
if (namaPadi != null) {
namaPadi = namaPadi.substring(0,1).toUpperCase() + namaPadi.substring(1).toLowerCase();
header = (TextView) findViewById(R.id.textView4);
String ni = header.getText().toString();
ni = ni + "\"" + namaPadi + "\"";
header.setText(ni);
}
ask = (TextView) findViewById(R.id.ask);
askgambar=(ImageView) findViewById(R.id.gambargejala);
}
public ArrayList<PohonKeputusan> setRelatedGejala(ArrayList<PohonKeputusan> phk){
ArrayList<PohonKeputusan> phkObjArr = new ArrayList<PohonKeputusan>();
for (int i = 0; i < phk.size(); i++){
boolean result = false;
PohonKeputusan phkObj = phk.get(i);
String gejalaKode = phkObj.gejala_kode;
for (int i2 = 0; i2 < gejalaPadi.length; i2++){
if(gejalaKode.equals(gejalaPadi[i2])){
result = true;
break;
}
}
if(result == true) phkObjArr.add(phkObj);
}
return phkObjArr;
}
public void rollbackQuestion(ArrayList<PohonKeputusan> phk){
qIndex = 0;
pohonKeputusan = phk.get(qIndex);
}
public void setQuestion(PohonKeputusan phk){
ask.setText(phk.gejala);
------------------------------------??????????----------------------------
}
What code i must input in that last line on that last line to set the image from name file from json?
Thanks you.

If I understand correctly you're trying to convert a String into a resource ID.
If that is the case, you can use getResources().getIdentifier(name, type, package)
Here is an example.
public void setQuestion(PohonKeputusan phk){
ask.setText(phk.gejala);
askgambar.setImageResource(getResources().getIdentifier(phk. gambar_gejala, "drawable", getPackageName()));
}

Related

Views are truncated when trying to add them at the same row using ConstraintLayout

I'm trying to create my own multi button "custom view" that get it's attributes from an xml file.
When trying to create a custom view with more than 3 button, some button are truncated (please see screenshot attached).
Maybe someone encounter an issue like that (maybe the problem related to wrong use of ConstraintLayout "Packed Chain" style).
Please notice that i have a Boolean parameter named "reversedOrder" in order to support some language that are written from RTL
My Programmatic code is:
public class MultiButton extends ConstraintLayout
{
public static final int MAX_NUMBER_OF_BUTTONS = 5;
#StyleableRes
private int indexNumOfButtons = 0;
#StyleableRes
private int indexOfOrder = 1;
#StyleableRes
private int indexOfActiveButtonIndex = 2;
#StyleableRes
private int indexOfBackgroundSelectorResource = 3;
#StyleableRes
private int indexOfTextcolorSelectorResource = 4;
private int numOfButtons;
private int activeButtonIndex;
private boolean reversedOrder;
private Button[] allButtons;
private View.OnClickListener[] additionalOnClickListeners;
public MultiButton(Context context, AttributeSet attrs )
{
super(context,attrs);
init(context,attrs);
}
private void init(Context context, AttributeSet attrs)
{
int[] sets = {R.attr.numOfButtons, R.attr.reversedOrder, R.attr.activeButtonIndex,R.attr.backgroundSelector,R.attr.textColorSelector};
TypedArray typedArray = context.obtainStyledAttributes(attrs, sets);
numOfButtons = typedArray.getInt(indexNumOfButtons,1);
if (numOfButtons < 0)
{
numOfButtons = 1;
}
else if (numOfButtons > MAX_NUMBER_OF_BUTTONS)
{
numOfButtons = MAX_NUMBER_OF_BUTTONS;
}
allButtons = new Button[numOfButtons];
int height = getHeight();
for (int i =0; i<numOfButtons; i++)
{
allButtons[i] = new Button(context);
allButtons[i].setText("" +i);
allButtons[i].setHeight(height);
allButtons[i].setWidth(0);
}
additionalOnClickListeners = new View.OnClickListener[numOfButtons];
int backgroundSelectorResourceId = typedArray.getResourceId(indexOfBackgroundSelectorResource,0); //context.getResources().getDrawable(R.drawable.btn);
int textColorSelectorResourceId = typedArray.getResourceId(indexOfTextcolorSelectorResource,0);
reversedOrder = typedArray.getBoolean(indexOfOrder,false);
for (int i=0; i< numOfButtons; i++)
{
int currentIndex = reversedOrder ? (numOfButtons-i-1) : i;
allButtons[currentIndex].setId(generateViewId());
addView(allButtons[currentIndex]);
if (backgroundSelectorResourceId != 0) {
Drawable buttonDrawable = context.getResources().getDrawable(backgroundSelectorResourceId);
if (buttonDrawable != null) {
buttonDrawable.mutate();
allButtons[currentIndex].setBackground(buttonDrawable);
}
}
if (textColorSelectorResourceId != 0)
{
ColorStateList colorStateList = context.getResources().getColorStateList(textColorSelectorResourceId);
if (colorStateList !=null) {
allButtons[currentIndex].setTextColor(colorStateList);
}
}
allButtons[currentIndex].setOnClickListener(new DefaultButtonListener(currentIndex));
}
ConstraintSet set = new ConstraintSet();
set.clone(this);
int[] chainIds = new int[numOfButtons];
float[] chainWeights = new float[numOfButtons];
for (int i=0; i<numOfButtons; i++)
{
int currentIndex = reversedOrder ? (numOfButtons-i-1) : i;
chainIds[currentIndex] = allButtons[currentIndex].getId();
chainWeights[currentIndex] = 1;
}
for (int i=1; i< numOfButtons ; i++)
{
if (reversedOrder)
{
set.connect(allButtons[i - 1].getId(), ConstraintSet.LEFT, allButtons[i].getId(), ConstraintSet.RIGHT);
}
else
{
set.connect(allButtons[i-1].getId(), ConstraintSet.RIGHT, allButtons[i].getId(),ConstraintSet.LEFT);
}
}
if (reversedOrder)
{
set.connect(allButtons[0].getId(),ConstraintSet.RIGHT,ConstraintSet.PARENT_ID,ConstraintSet.RIGHT);
set.connect(allButtons[numOfButtons-1].getId(),ConstraintSet.LEFT,ConstraintSet.PARENT_ID,ConstraintSet.LEFT);
}
else
{
set.connect(allButtons[0].getId(),ConstraintSet.LEFT,ConstraintSet.PARENT_ID,ConstraintSet.LEFT);
set.connect(allButtons[numOfButtons-1].getId(),ConstraintSet.RIGHT,ConstraintSet.PARENT_ID,ConstraintSet.RIGHT);
}
set.createHorizontalChain(ConstraintSet.PARENT_ID,ConstraintSet.LEFT, ConstraintSet.PARENT_ID,ConstraintSet.RIGHT,chainIds,chainWeights,ConstraintSet.CHAIN_PACKED);
set.applyTo(this);
activeButtonIndex = typedArray.getInt(indexOfActiveButtonIndex,0);
if (activeButtonIndex < 0 && activeButtonIndex > MAX_NUMBER_OF_BUTTONS -1)
{
activeButtonIndex = 0;
}
allButtons[activeButtonIndex].setSelected(true);
}
}
xml layout:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/helloWorld"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.example.customviewapp.MultiButton
android:layout_width="300dp"
android:layout_height="50dp"
app:layout_constraintTop_toBottomOf="#id/helloWorld"
android:layout_marginTop="15dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:numOfButtons="4"
app:activeButtonIndex="0"
/>
</androidx.constraintlayout.widget.ConstraintLayout>

Football-data API JSON parsing error

I'm having difficulty in downloading footballing data from an (http://www.football-data.org). I am trying to download the English Premier League Table by creating a new Standing object for each team and adding them to an ArrayList.
I've set up my parser class, adapter class and my view.
The error I am getting is :
org.json.JSONException: org.json.JSONException: Value {"_links":{"self":{"href":"http:\/\/api.football-data.org\/v1\/soccerseasons\/426\/leagueTable\/?matchday=37"},"soccerseason":{"href":"http:\/\/api.football-data.org\/v1\/soccerseasons\/426"}},"leagueCaption":"Premier League 2016\/17","matchday":37,"standing":[{"_links":{"team":{"href":"http:\/\/api.football-data.org\/v1\/teams\/61"}},"position":1,"teamName":"Chelsea FC","crestURI":"http:\/\/upload.wikimedia.org\/wikipedia\/de\/5\/5c\/Chelsea_crest.svg","playedGames":36,"points":87,"goals":76,"goalsAgainst":29,"goalDifference":47,"wins":28,"draws":3,"losses":5,"home":{"goals":46,"goalsAgainst":13,"wins":15,"draws":0,"losses":2},"away":{"goals":30,"goalsAgainst":16,"wins":13,"draws":3,"losses":3}},{"_links":{"team":{"href":"http:\/\/api.football-data.org\/v1\/teams\/73"}},"position":2,"teamName":"Tottenham Hotspur FC","crestURI":"http:\/\/upload.wikimedia.org\/wikipedia\/de\/b\/b4\/Tottenham_Hotspur.svg","playedGames":35,"points":77,"goals":71,"goalsAgainst":23,"goalDifference":48,"wins":23,"draws":8,"losses":4,"home":{"goals":45,"goalsAgainst":8,"wins":16,"draws":2,"losses":0},"away":{"goals":26,"goalsAgainst":15,"wins":7,"draws":6,"losses":4}},{"_links":{"team":{"href":"http:\/\/api.football-data.org\/v1\/teams\/65"}},"position":3,"teamName":"Manchester City FC","crestURI":"https:\/\/upload.wikimedia.org\/wikipedia\/en\/e\/eb\/Manchester_City_FC_badge.svg","playedGames":36,"points":72,"goals":72,"goalsAgainst":38,"goalDifference":34,"wins":21,"draws":9,"losses":6,"home":{"goals":34,"goalsAgainst":16,"wins":10,"draws":7,"losses":1},"away":{"goals":38,"goalsAgainst":22,"wins":11,"draws":2,"losses":5}},{"_links":{"team":{"href":"http:\/\/api.football-data.org\/v1\/teams\/64"}},"position":4,"teamName":"Liverpool FC","crestURI":"http:\/\/upload.wikimedia.org\/wikipedia\/de\/0\/0a\/FC_Liverpool.svg","playedGames":36,"points":70,"goals":71,"goalsAgainst":42,"goalDifference":29,"wins":20,"draws":10,"losses":6,"home":{"goals":42,"goalsAgainst":18,"wins":11,"draws":5,"losses":2},"away":{"goals":29,"goalsAgainst":24,"wins":9,"draws":5,"losses":4}},{"_links":{"team":{"href":"http:\/\/api.football-data.org\/v1\/teams\/57"}},"position":5,"teamName":"Arsenal FC","crestURI":"http:\/\/upload.wikimedia.org\/wikipedia\/en\/5\/53\/Arsenal_FC.svg","playedGames":35,"points":66,"goals":68,"goalsAgainst":42,"goalDifference":26,"wins":20,"draws":6,"losses":9,"home":{"goals":34,"goalsAgainst":15,"wins":12,"draws":3,"losses":2},"away":{"goals":34,"goalsAgainst":27,"wins":8,"draws":3,"losses":7}},{"_links":{"team":{"href":"http:\/\/api.football-data.org\/v1\/teams\/66"}},"position":6,"teamName":"Manchester United FC","crestURI":"http:\/\/upload.wikimedia.org\/wikipedia\/de\/d\/da\/Manchester_United_FC.svg","playedGames":35,"points":65,"goals":51,"goalsAgainst":27,"goalDifference":24,"wins":17,"draws":14,"losses":4,"home":{"goals":24,"goalsAgainst":12,"wins":7,"draws":10,"losses":1},"away":{"goals":27,"goalsAgainst":15,"wins":10,"draws":4,"losses":3}},{"_links":{"team":{"href":"http:\/\/api.football-data.org\/v1\/teams\/62"}},"position":7,"teamName":"Everton FC","crestURI":"http:\/\/upload.wikimedia.org\/wikipedia\/de\/f\/f9\/Everton_FC.svg","playedGames":37,"points":61,"goals":61,"goalsAgainst":41,"goalDifference":20,"wins":17,"draws":10,"losses":10,"home":{"goals":42,"goalsAgainst":16,"wins":13,"draws":4,"losses":2},"away":{"goals":19,"goalsAgainst":25,"wins":4,"draws":6,"losses":8}},{"_links":{"team":{"href":"http:\/\/api.football-data.org\/v1\/teams\/74"}},"position":8,"teamName":"West Bromwich Albion FC","crestURI":"http:\/\/upload.wikimedia.org\/wikipedia\/de\/8\/8b\/West_Bromwich_Albion.svg","playedGames":36,"points":45,"goals":41,"goalsAgainst":46,"goalDifference":-5,"wins":12,"draws":9,"losses":15,"home":{"goals":27,"goalsAgainst":22,"wins":9,"draws":2,"losses":8},"away":{"goals":14,"goalsAgainst":24,"wins":3,"draws":7,"losses":7}},{"_links":{"team":{"href":"http:\/\/api.football-data.org\/v1\/teams\/1044"}},"position":9,"teamName":"AFC Bournemouth","crestURI":"https:\/
05-13 15:39:24.798 6021-6540/com.example.oisin.premierleaguesocial W/System.err: at org.json.JSON.typeMismatch(JSON.java:111)
05-13 15:39:24.798 6021-6540/com.example.oisin.premierleaguesocial W/System.err: at org.json.JSONArray.<init>(JSONArray.java:96)
05-13 15:39:24.798 6021-6540/com.example.oisin.premierleaguesocial W/System.err: at org.json.JSONArray.<init>(JSONArray.java:108)
05-13 15:39:24.798 6021-6540/com.example.oisin.premierleaguesocial W/System.err: at com.example.oisin.premierleaguesocial.Utilities.JSONParser.parse(JSONParser.java:75)
05-13 15:39:24.799 6021-6540/com.example.oisin.premierleaguesocial W/System.err: at com.example.oisin.premierleaguesocial.Utilities.JSONParser.doInBackground(JSONParser.java:56)
05-13 15:39:24.799 6021-6540/com.example.oisin.premierleaguesocial W/System.err: at com.example.oisin.premierleaguesocial.Utilities.JSONParser.doInBackground(JSONParser.java:27)
I've been trying to resolve the issue for a few hours, but can't fix it. I think I've set up my data types correctly. I decided to only try to get the Integer data types at first for the sake of simplicity.
Any help would be very much appreciated. Thank you.
public class JSONParser extends AsyncTask<Void, Void, Boolean> {
private Context c;
private String jsonData;
private RecyclerView rv;
private ProgressDialog pd;
private ArrayList<Standing> mLeagueTable = new ArrayList<>();
public JSONParser(Context c, String jsonData, RecyclerView rv) {
this.c = c;
this.jsonData = jsonData;
this.rv = rv;
}
#Override
protected void onPreExecute () {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("Parse");
pd.setMessage("Parsing..Please Wait");
pd.show();
}
#Override
protected Boolean doInBackground (Void...params){
return parse();
}
#Override
protected void onPostExecute (Boolean isParsed){
super.onPostExecute(isParsed);
pd.dismiss(); //Dismiss progress dialog.
if (isParsed) {
//BIND
rv.setAdapter(new TableAdapter(c, mLeagueTable)); //Pass in instance of adapter.
} else {
Toast.makeText(c, "Unable to Parse check your Log Output", Toast.LENGTH_SHORT).show();
}
}
private Boolean parse() {
try {
//JSONArray ja = new JSONArray(jsonData);
JSONArray ja = new JSONArray("standing");
JSONObject jo; //declare json OBJECT
mLeagueTable.clear(); //Clears the ArrayList.
Standing table; //Declare a table
for (int i = 0; i < ja.length(); i++) //iterating in JSONArray
{
jo = ja.getJSONObject(i);
int position = ja.getInt(Integer.parseInt("position"));
int points = ja.getInt(Integer.parseInt("points"));
int playedGames = ja.getInt(Integer.parseInt("playedGames"));
int goals = ja.getInt(Integer.parseInt("goals"));
int goalsAgainst = ja.getInt(Integer.parseInt("goalsAgainst"));
int goalDifference = ja.getInt(Integer.parseInt("goalDifference"));
table = new Standing(); //Create a new "User" object.
table.setPosition(position);
table.setPoints(points);
table.setPlayedGames(playedGames);
table.setGoals(goals);
table.setGoalsAgainst(goalsAgainst);
table.setGoalDifference(goalDifference);
mLeagueTable.add(table); //Add new Standing object to ArrayList mLeagueTable.
}
return true;
} catch (JSONException e) {
e.printStackTrace();
return false;
}
}
}
public class JSONDownloader extends AsyncTask<Void, Void, String> {
Context c;
String jsonURL;
RecyclerView rv;
ProgressDialog pd;
public JSONDownloader(Context c, String jsonURL, RecyclerView rv) {
this.c = c;
this.jsonURL = jsonURL;
this.rv = rv;
}
#Override
protected void onPreExecute() { //CALLED just before data is downloaded.
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("Download JSON");
pd.setMessage("Downloading.... Please Wait!");
pd.show();
}
#Override
protected String doInBackground(Void... voids) {
return download();
}
#Override
protected void onPostExecute(String jsonData) {
super.onPostExecute(jsonData);
pd.dismiss();
if (jsonData.startsWith("Error"))
{
String error = jsonData;
Toast.makeText(c, error, Toast.LENGTH_SHORT).show();
} else {
//PARSER
new JSONParser(c, jsonData, rv).execute();
}
}
private String download() {
Object connection = Connector.connect(jsonURL);
if (connection.toString().startsWith("Error")) {
return connection.toString();
}
try {
HttpURLConnection con = (HttpURLConnection) connection; //Cast connection to HTTPConnection
if (con.getResponseCode() == con.HTTP_OK) {
//GET INPUT FROM STREAM
InputStream is = new BufferedInputStream(con.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer jsonData = new StringBuffer();
// READ
while ((line = br.readLine()) != null) {
jsonData.append(line + "\n");
}
//CLOSE RESOURCES
br.close();
is.close();
//RETURN JSON
return jsonData.toString();
} else {
return "Error " + con.getResponseMessage();
}
} catch (IOException e) {
e.printStackTrace();
return "Error " + e.getMessage();
}
}
}
public class MainActivity extends AppCompatActivity {
String jsonURL = "http://api.football-data.org/v1/soccerseasons/426/leagueTable";
public static final String TAG = "MainActivity";
//FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
private RecyclerView rv;
/*private ArrayList<Standing> mLeagueTable = new ArrayList<>(); //Initalise m
private TableAdapter mTableAdapter = new TableAdapter(mLeagueTable, this); */
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_table);
//Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
rv = (RecyclerView) findViewById(R.id.rv);
if (rv != null) {
rv.setLayoutManager(new LinearLayoutManager(this));
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); //Initialze FAB
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONDownloader(MainActivity.this, jsonURL, rv).execute();
}
});
}
}
public class TableAdapter extends RecyclerView.Adapter<MyViewHolder>{
private ArrayList<Standing> mLeagueTable;
private Context c;
public TableAdapter(Context c, ArrayList<Standing> mLeagueTable) {
this.c = c;
this.mLeagueTable = mLeagueTable;
} //Constructor
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.tableitem, parent, false); //Inlfate the League Table model view.
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) { //BINDS THE data to the appropriote View
Standing s = mLeagueTable.get(position);
final int teamPosition = s.getPosition();
final String teamName = s.getTeamName();
final int playedGames = s.getPlayedGames();
final int goals = s.getGoals();
final int goalsAgainst = s.getGoalsAgainst();
final int goalDifference = s.getGoalDifference();
final int points = s.getPoints();
//holder.teamNameTxt.setText(teamName);
holder.teamPositionTxt.setText(teamPosition);
holder.playedGamesTxt.setText(playedGames);
//holder.teamImage.setImageResource(s.getTeamImage());
holder.goalsTxt.setText(goals);
holder.goalsAgainstTxt.setText(goalsAgainst);
holder.goalDifferenceTxt.setText(goalDifference);
holder.pointsTxt.setText(points);
// holder.wins.setText(s.getWins());
//holder.draws.setText(s.getDraws());
//holder.losses.setText(s.getLosses());
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(int pos) {
openActivity(teamPosition, playedGames, goals, goalsAgainst, goalDifference, points);
}
});
}
#Override
public int getItemCount() {return mLeagueTable.size();}
////open Activity
private void openActivity(int...details)
{
Intent i = new Intent(c, TableActivity.class);
i.putExtra("POSITION_KEY", details[0]);
//i.putExtra("TEAMNAME_KEY", details[1]);
i.putExtra("POINTS_KEY", details[2]);
i.putExtra("PLAYEDGAMES_KEY", details[3]);
i.putExtra("GOALS_KEY", details[4]);
i.putExtra("GOALSAGAINST_KEY", details[5]);
i.putExtra("GOALDIFFERENCE_KEY", details[6]);
c.startActivity(i);
}
}
tableitem.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/teamPositionTxt"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#color/primary_text" />
<TextView
android:id="#+id/teamNameTxt"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:textColor="#color/primary_text" />
<TextView
android:id="#+id/pointsTxt"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#color/primary_text"
android:textStyle="bold" />
<TextView
android:id="#+id/playedGamesTxt"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#color/primary_text" />
<TextView
android:id="#+id/goalsTxt"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#color/primary_text" />
<TextView
android:id="#+id/goalsAgainstTxt"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#color/primary_text" />
<TextView
android:id="#+id/goalDifferenceTxt"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#color/primary_text" />
</LinearLayout>
1. Create a JSONObject from string jsonData.
2. Get JSONArray (standing) from JSONObject by using jsonObj.getJSONArray("standing").
3. Inside for loop, get int values from JsonObject using jo.getInt() instead of ja.getInt().
Here is the working code:
private Boolean parse() {
try {
JSONObject jsonObj = new JSONObject(jsonData);
JSONArray ja = jsonObj.getJSONArray("standing");
mLeagueTable.clear(); //Clears the ArrayList.
for (int i = 0; i < ja.length(); i++) //iterating in JSONArray
{
JSONObject jo = ja.getJSONObject(i);
int position = jo.getInt(Integer.parseInt("position"));
int points = jo.getInt(Integer.parseInt("points"));
int playedGames = jo.getInt(Integer.parseInt("playedGames"));
int goals = jo.getInt(Integer.parseInt("goals"));
int goalsAgainst = jo.getInt(Integer.parseInt("goalsAgainst"));
int goalDifference = jo.getInt(Integer.parseInt("goalDifference"));
Standing table = new Standing(); //Create a new "User" object.
table.setPosition(position);
table.setPoints(points);
table.setPlayedGames(playedGames);
table.setGoals(goals);
table.setGoalsAgainst(goalsAgainst);
table.setGoalDifference(goalDifference);
mLeagueTable.add(table); //Add new Standing object to ArrayList mLeagueTable.
}
return true;
} catch (JSONException e) {
e.printStackTrace();
return false;
}
}
Hope this will work~
Change
JSONArray ja = new JSONArray("standing");
for
JSONObject ja = new JSONObject(jsonData);
JSONObject jo = ja.getJSONObject("soccerseason");
The information is in jo, and now you can extract each field following the right structure of the JSONObject

Android Studio (Java): Continue prime number for loop on button press

I want to be able to display the next prime number each time the button is clicked but cannot find a way for it to work. Anybody help please?
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button primeButton = (Button) findViewById(R.id.primeButton);
primeButton.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View v){
TextView primeText = (TextView) findViewById(R.id.primeText);
int max = 500;
for(int i=2; i<=max; i++) {
boolean isPrimeNumber = true;
for (int j = 2; j <= i; j++) {
if (i % j == 0 ) {
isPrimeNumber = false;
break;
}
}
if (isPrimeNumber){
primeText.setText(Integer.toString(i));
}
}
}
}
);
}
}
Try this
public class MainActivity extends Activity {
Button b;
int max = 500;
TextView vTextView;
int j = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.button1);
vTextView = (TextView) findViewById(R.id.textView1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
for (int i = j; i <= max; i++) {
if (isPrimeNumber(i)) {
vTextView.setText(i+"");
j = i+1;
break;
}
}
}
});
}
public boolean isPrimeNumber(int number) {
for (int i = 2; i <= number / 2; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
To find out a prime number, prime numbers between two numbers and sum of a prime number
public class MainActivity extends AppCompatActivity {
private EditText etInput;
private EditText et_from, et_to;
private Button btnCheck, btn_print;
private TextView tvResult;
private int inputnumber;
private int fromNumber, toNumber;
private boolean isPrimeNumber = true;
private TextView tv_prime_sum;
private int primeNumbersSum;
private TextView tv_check;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViews();
btnCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!(etInput.getText().toString().trim() != null && etInput.getText().toString().trim().length() > 0)) {
etInput.setError("Please enter the number");
} else {
inputnumber = Integer.parseInt(etInput.getText().toString());
for (int i = 2; i <= inputnumber / 2; i++) {
if (inputnumber % i == 0) {
isPrimeNumber = false;
break;
}
}
if (isPrimeNumber) {
tv_check.setText("The given number " + inputnumber + " is a prime number");
} else {
tv_check.setText("The given number " + inputnumber + " is not a prime number");
}
isPrimeNumber = true;
}
}
});
btn_print.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!(et_from.getText().toString().trim() != null && et_from.getText().toString().trim().length() > 0)) {
et_from.setError("Please enter the number");
} else if (!(et_to.getText().toString().trim() != null && et_to.getText().toString().trim().length() > 0)) {
et_to.setError("Please enter the number");
} else {
fromNumber = Integer.parseInt(et_from.getText().toString());
toNumber = Integer.parseInt(et_to.getText().toString());
if (fromNumber > toNumber) {
fromNumber = fromNumber - toNumber;
toNumber = fromNumber + toNumber;
fromNumber = toNumber - fromNumber;
}
StringBuilder stringBuilder = new StringBuilder();
for (int j = fromNumber; j <= toNumber; j++) {
for (int i = 2; i <= j / 2; i++) {
if (j % i == 0) {
isPrimeNumber = false;
break;
} else {
isPrimeNumber = true;
}
}
if (isPrimeNumber) {
Log.v("Primenumber", "list" + j);
primeNumbersSum = primeNumbersSum + j;
stringBuilder.append(j);
stringBuilder.append(",");
} else {
}
}
tvResult.setText(stringBuilder.toString());
tv_prime_sum.setText("Total sum of prime numbers: " + primeNumbersSum);
isPrimeNumber = true;
primeNumbersSum = 0;
}
}
});
}
private void findViews() {
etInput = findViewById(R.id.et_input);
btnCheck = findViewById(R.id.btn_check);
tvResult = findViewById(R.id.tv_result);
tv_prime_sum = findViewById(R.id.tv_prime_sum);
et_from = findViewById(R.id.et_from);
et_to = findViewById(R.id.et_to);
btn_print = findViewById(R.id.btn_print);
tv_check = findViewById(R.id.tv_check);
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="#+id/et_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="enter the number"
android:inputType="number"
android:visibility="visible" />
<Button
android:id="#+id/btn_check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/et_input"
android:layout_centerHorizontal="true"
android:layout_margin="10dp"
android:text="Check" />
<TextView
android:id="#+id/tv_check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/btn_check"
android:layout_centerHorizontal="true"
android:layout_margin="10dp"
android:text="print the number is prime or not" />
<EditText
android:id="#+id/et_from"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tv_check"
android:hint="from number"
android:inputType="number" />
<EditText
android:id="#+id/et_to"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/et_from"
android:hint="to number"
android:inputType="number" />
<Button
android:id="#+id/btn_print"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/et_to"
android:layout_centerHorizontal="true"
android:layout_margin="10dp"
android:text="Print" />
<TextView
android:id="#+id/tv_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/btn_print"
android:layout_centerHorizontal="true"
android:text="prints the list of prime numbers" />
<TextView
android:id="#+id/tv_prime_sum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tv_result"
android:layout_centerHorizontal="true"
android:layout_margin="10dp" />
</RelativeLayout>

How i can create paging in my page for epub ? android

How i can create paging for my WebView that fill from Epub.
My MainActivity.java :
public class MainActivity extends ActionBarActivity implements OnClickListener {
WebView webView;
Handler hand;
String data = null;
LinearLayout books;
int pagecount = 1;
Book book;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hand = new Handler();
webView = new WebView(this);
books = (LinearLayout) findViewById(R.id.book);
AssetManager assetManager = getAssets();
try {
InputStream epubInputStream = assetManager.open("mybook.epub");
book = (new EpubReader()).readEpub(epubInputStream);
Log.i("Log_one", "author(s): " + book.getMetadata().getAuthors());
Log.i("Log_two", "title: " + book.getTitle());
Bitmap coverImage = BitmapFactory.decodeStream(book.getCoverImage().getInputStream());
Log.i("Log_three", "Coverimage is " + coverImage.getWidth() + " by " + coverImage.getHeight() + " pixels");
logTableOfContents(book.getTableOfContents().getTocReferences(), 0);
Spine spine = book.getSpine();
List<SpineReference> spineList = spine.getSpineReferences();
int count = spineList.size();
Button btnnext = (Button) findViewById(R.id.btnNext);
Button btnPreviuse = (Button) findViewById(R.id.btnPreviuse);
btnnext.setOnClickListener(this);
btnPreviuse.setOnClickListener(this);
} catch (IOException e) {
Log.e("Log_four", e.getMessage());
}
}
private void logTableOfContents(List<TOCReference> tocReferences, int depth) {
if (tocReferences == null) {
return;
}
for (TOCReference tocReference : tocReferences) {
StringBuilder tocString = new StringBuilder();
for (int i = 0; i < depth; i++) {
tocString.append("\t");
}
tocString.append(tocReference.getTitle());
Log.i("Log_five", tocString.toString());
logTableOfContents(tocReference.getChildren(), depth + 1);
}
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btnNext) {
try {
int i = pagecount + 7;
webView = new WebView(this);
books = (LinearLayout) findViewById(R.id.book);
data = new String(book.getContents().get(i).getData());
webView.loadDataWithBaseURL("file:///android_asset/", data, "text/html", "UTF-8", null);
books.addView(webView);
} catch (IOException e) {
e.printStackTrace();
}
} else if (v.getId() == R.id.btnPreviuse) {
try {
int i = pagecount - 1;
webView = new WebView(this);
books = (LinearLayout) findViewById(R.id.book);
data = new String(book.getContents().get(i).getData());
webView.loadDataWithBaseURL("file:///android_asset/", data, "text/html", "UTF-8", null);
books.addView(webView);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
When i click on Button I need to see another page but i can't see .
My activity_main.xml :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/book"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical" >
</LinearLayout>
<LinearLayout
android:id="#+id/Footer"
android:layout_width="match_parent"
android:layout_height="100dip"
android:layout_weight="1"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<Button
android:id="#+id/btnNext"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="0.5"
android:text="Next Page" />
<Button
android:id="#+id/btnPreviuse"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="0.5"
android:text="Previuse Page" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
How i can create paging on my page .
#Override
public void onClick(View v) {
if(v.getId() == R.id.btnNext){
try {
books.removeAllViews();
int i = pagecount + y;
y = i;
webView = new WebView(this);
books = (LinearLayout) findViewById(R.id.book);
data = new String(book.getContents().get(y).getData());
webView.loadDataWithBaseURL("file:///android_asset/", data, "text/html", "UTF-8", null);
books.addView(webView);
} catch (IOException e) {
e.printStackTrace();
}
}else if(v.getId() == R.id.btnPreviuse){
try {
books.removeAllViews();
int i = y - pagecount;
y = i;
webView = new WebView(this);
books = (LinearLayout) findViewById(R.id.book);
data = new String(book.getContents().get(y).getData());
webView.loadDataWithBaseURL("file:///android_asset/", data, "text/html", "UTF-8", null);
books.addView(webView);
} catch (IOException e) {
e.printStackTrace();
}
}
}

how to implement search directly from server

I want to implement search directly from the data on server. For example search from google.com. A edittext, like in search bar of google a word in edittext then it hits the server and fetch the records starting from that word.
public class SearchActivity extends Activity {
TextView imeino;
Spinner select;
EditText searchby;
StringBuffer URL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
imeino = (TextView)findViewById(R.id.getimeino);
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String device_id = tm.getDeviceId();
imeino.setText(device_id);
searchby = (AutoCompleteTextView)findViewById(R.id.editText1);
//this is a spinner if i choose mobile from this then edittext only takes numeric value.and if a select name then it takes alphabets.
select = (Spinner)findViewById(R.id.spinner1);
select.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
if(select.getSelectedItem().toString().equals("Mobile"))
{
searchby.setInputType(InputType. TYPE_CLASS_PHONE|InputType.TYPE_TEXT_VARIATION_PHONETIC);
}
if(select.getSelectedItem().toString().equals("name"))
{
searchby.setInputType(InputType. TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PERSON_NAME);
}
if(select.getSelectedItem().toString().equals("Address"))
{
searchby.setInputType(InputType. TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_POSTAL_ADDRESS);
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
this is my edittext in which i have to search for data
searchby.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
searchby = (AutoCompleteTextView)findViewById(R.id.editText1);
String getitemforsearch = searchby.getText().toString();
SearchFromCustomerData(getitemforsearch);
}
public void SearchFromCustomerData(String getitemforsearch) {
String searchType= new String();
if(select.getSelectedItem().toString().equals("Mobile"))
{
searchType= "CustomerMobile";
}
if(select.getSelectedItem().toString().equals("Address"))
{
searchType= "CustomerAddress";
}
if(select.getSelectedItem().toString().equals("name"))
{
searchType= "CustomerName";
}
This is my url to hit web service and it will show options
URL = new StringBuffer("?"+searchType+"=" + getitemforsearch+"&searchType="+searchType);
try {
URL sever = new URL(URL.toString());
System.out.println(URL.toString());
URLConnection yc = sever.openConnection();
InputStream in = yc.getInputStream(); // Get the data in the entity
InputStreamReader is = new InputStreamReader(in);
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(is);
String read = br.readLine();
while (read != null) {
sb.append(read);
read = br.readLine();
}
JSONObject jsonObject = new JSONObject(sb.toString());
JSONArray resultArray = jsonObject.getJSONArray("Customer");
System.out.println(" Length :" + resultArray.length());
String[] CustomerCode = new String[resultArray.length()];
String[] CustomerName = new String[resultArray.length()];
String[] CustomerEmail = new String[resultArray.length()];
String[] CustomerMobile = new String[resultArray.length()];
String[] Customeraddress = new String[resultArray.length()];
for (int i = 0; i < resultArray.length(); i++) {
JSONObject object = (JSONObject) resultArray.get(i);
System.out.println("true");
CustomerCode[i] = object.getString("CustomerCode") == null ? "" : object.getString("CustomerCode");
CustomerName[i] = object.getString("CustomerName") == null ? "" : object.getString("CustomerName");
CustomerEmail[i] = object.getString("CustomerEmailId") == null ? "" : object.getString("CustomerEmailId");
CustomerMobile[i] = object.getString("CustomerMobile") == null ? "" : object.getString("CustomerMobile");
Customeraddress[i] = object.getString("CustomerAddress") == null ? "" : object.getString("CustomerAddress");
}
}
catch (Exception e) {
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
}
here is my layout file..
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".SearchActivity" >
<TextView
android:id="#+id/getimeino"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:hint="ImEiNo..." />
<Spinner
android:id="#+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/getimeino"
android:layout_marginTop="30dp"
android:entries="#array/process_arrays"
android:prompt="#string/process_prompt" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/getimeino"
android:layout_centerHorizontal="true"
android:ems="10" >
<requestFocus />
</EditText>
</RelativeLayout>

Categories

Resources