Android populate spinner with string array - android

Below I have attached my code for trying to add my string array, names, to the spinner as the options. As of now, I am not getting anything populating the array, and I am really not sure what I'm doing wrong. I have looked over other similar questions on this site, as well as using Google, and have come up empty. Can anyone give me some guidance? Thanks
public class RunesActivity extends Activity {
public static String page;
TextView textName;
Spinner spinner;
ArrayAdapter<String> adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rune_activity);
GetRunes getRunes = new GetRunes();
getRunes.execute();
spinner = (Spinner) findViewById(R.id.rune_selector);
}
public void addListenerOnSpinnerSelection() {
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
((TextView) adapterView.getChildAt(0)).setTextColor(Color.parseColor("#C49246"));
Toast.makeText(adapterView.getContext(),
"Page Selected: " + adapterView.getItemAtPosition(i).toString(),
Toast.LENGTH_SHORT).show();
page = adapterView.getItemAtPosition(i).toString();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
class GetRunes extends AsyncTask<String, String, JSONObject> {
private String api_key="d96236d2-6ee3-4cfd-afa7-f41bdbc11128";
String region = MainActivity.region.toLowerCase();
String id = StatsActivity.sumID;
String encodedKey = null;
String encodedRegion = null;
String encodedId = null;
String url = null;
// JSON Node Names
String TAG_NAME = "name";
String TAG_CURRENT = "current";
String TAG_SLOTS = "slots";
String TAG_RUNEID = "runeId";
String TAG_RUNESLOTID = "runeSlotId";
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
// Assign views
textName = (TextView) findViewById(R.id.name);
// Encode URL variables
encodedId = URLEncoder.encode(id, "UTF-8");
encodedKey = URLEncoder.encode(api_key, "UTF-8");
encodedRegion = URLEncoder.encode(region, "UTF-8");
url = "http://prod.api.pvp.net/api/lol/" + region + "/v1.4/summoner/" + id + "/runes?api_key=" + api_key;
Log.i("..........", url);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
#Override
protected JSONObject doInBackground(String... arg0) {
JSONParser jParser = new JSONParser();
// Get JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
Log.i("............", "" + json);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
// Get JSON Object
JSONObject runes = json.getJSONObject(encodedId);
// Get JSON Array node
JSONArray rune = runes.getJSONArray("pages");
// Loop through pages, page names stored in string array
String[] name = new String[rune.length()];
String curr;
ArrayList<String> runePageNames = new ArrayList<String>();
for(int i = 0; i < rune.length(); i++) {
JSONObject c = rune.getJSONObject(i);
name[i] = c.getString(TAG_NAME);
curr = c.getString(TAG_CURRENT);
if(curr.equals("true"))
name[i] = name[i] + " [Active]";
runePageNames.add(name[i]);
Log.i(".........", name[i]);
}
adapter = new ArrayAdapter(RunesActivity.this,
android.R.layout.simple_spinner_dropdown_item,
runePageNames);
addListenerOnSpinnerSelection();
// Set TextView
textName.setText(name[0]);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}

Try this..
before calling addListenerOnSpinnerSelection(); method set adapter for that spinner.
adapter = new ArrayAdapter(RunesActivity.this,
android.R.layout.simple_spinner_dropdown_item,
runePageNames);
spinner.setAdapter(adapter );
addListenerOnSpinnerSelection();

Related

How do i pass data from listview to another listview

How do i pass from a listview when clicked to another listview in the next activity? I retrieved my data in my database, i am trying to filter the selection by their ID and show everything from the same id when i click an item from my listview.
Here is my onclick listview in my first activity
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent (this, Sample.class);
HashMap<String,String> map =(HashMap)parent.getItemAtPosition(position);
String s_id = map.get(Config.TAG_s_id).toString();
String s_name = map.get(Config.TAG_s_name).toString();
String s_gender = map.get(Config.TAG_s_gender).toString();
String teamone = map.get(Config.TAG_teamone).toString();
String teamonepts = map.get(Config.TAG_teamonepts).toString();
String teamtwo = map.get(Config.TAG_teamtwo).toString();
String teamtwopts = map.get(Config.TAG_teamtwopts).toString();
intent.putExtra(Config.S_id,s_id);
intent.putExtra(Config.S_name,s_name);
intent.putExtra(Config.S_gender,s_gender);
intent.putExtra(Config.Teamone,teamone);
intent.putExtra(Config.Teamonepts,teamonepts);
intent.putExtra(Config.Teamtwo,teamtwo);
intent.putExtra(Config.Teamtwopts,teamtwopts);
startActivity(intent);
}
Here is my second activity
editTextId = (EditText) findViewById(R.id.editTextId);
title1ID = (TextView) findViewById(R.id.s_genderID);
contentID = (TextView) findViewById(R.id.s_nameID);
dateID = (TextView) findViewById(R.id.teamone);
teamoneptsID = (TextView) findViewById(R.id.teamonepts);
teamtwoID = (TextView) findViewById(R.id.teamtwo);
teamtwoptsID = (TextView) findViewById(R.id.teamtwopts);
listview = (ListView) findViewById(R.id.listView);
Typeface font = Typeface.createFromAsset(getAssets(), "arial.ttf");
title1ID.setTypeface(font);
contentID.setTypeface(font);
dateID.setTypeface(font);
editTextId.setText(id);
title1ID.setText(titl);
contentID.setText(cont);
dateID.setText(date);
teamoneptsID.setText(teamonepts);
teamtwoID.setText(teamtwo);
teamtwoptsID.setText(teamtwopts);
getResult();
private void getResult() {
class GetResult extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
showResult(s);
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequestParam(Config.URL_Sport1, id);
return s;
}
}
GetResult ge = new GetResult();
ge.execute();
}
private void showResult(String json) {
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY1);
JSONObject c = result.getJSONObject(0);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void showResult(){
JSONObject jsonObject = null;
ArrayList<HashMap<String,String>> list = new ArrayList<>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY2);
for(int i = 0; i<result.length(); i++){
JSONObject jo = result.getJSONObject(i);
String teamone = jo.getString(Config.TAG_teamone);
String teamonepts = jo.getString(Config.TAG_teamonepts);
String teamtwo = jo.getString(Config.TAG_teamtwo);
String teamtwopts = jo.getString(Config.TAG_teamtwopts);
String s_name = jo.getString(Config.TAG_s_name);
String s_gender = jo.getString(Config.TAG_s_gender);
HashMap<String,String> match = new HashMap<>();
match.put(Config.TAG_teamone, teamone);
match.put(Config.TAG_teamonepts,teamonepts);
match.put(Config.TAG_teamtwo,teamtwo);
match.put(Config.TAG_teamtwopts,teamtwopts);
match.put(Config.TAG_s_name,s_name);
match.put(Config.TAG_s_gender,s_gender);
list.add(match);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(
Sample.this, list, R.layout.gamesadapterlayout,
new String[]{Config.TAG_teamone,Config.TAG_teamonepts, Config.TAG_teamtwo, Config.TAG_teamtwopts, Config.TAG_s_name, Config.TAG_s_gender},
new int[]{ R.id.team1, R.id.score1, R.id.team2, R.id.score2, R.id.Type, R.id.s_gender});
listview.setAdapter(adapter);
}
I am trying to put everything from my first activity into the next in a listview by taking all of the same id with the clicked item. What im getting instead is a textview of the same id with only 1 result and not in a listview.
Can someone help me please.

I am trying to parse a data from the following link

"http://soccer.sportsopendata.net/v1/leagues/premier-league/seasons/16-17/standings" - Link Which Iam Trying to parse
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button GetServerData = (Button) findViewById(R.id.GetServerData);
GetServerData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// WebServer Request URL
String serverURL = "http://soccer.sportsopendata.net/v1/leagues/premier-league/seasons/16-17/standings";
// Use AsyncTask execute Method To Prevent ANR Problem
new LongOperation().execute(serverURL);
}
});
}
private class LongOperation extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
String data = "";
TextView uiUpdate = (TextView) findViewById(R.id.textView2);
TextView jsonParsed = (TextView) findViewById(R.id.textView3);
int sizeData = 0;
EditText serverText = (EditText) findViewById(R.id.textView);
protected void onPreExecute() {
// NOTE: You can call UI Element here.
//Start Progress Dialog (Message)
Dialog.setMessage("Please wait..");
Dialog.show();
try {
// Set Request parameter
data += "&" + URLEncoder.encode("data", "UTF-8") + "=" + serverText.getText();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server ***********/
BufferedReader reader = null;
// Send data
try {
// Defined URL where to send data
URL url = new URL(urls[0]);
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line + "");
}
// Append Server Response To Content String
Content = sb.toString();
} catch (Exception e) {
Error = e.getMessage();
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
return null;
}
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
// Close progress dialog
Dialog.dismiss();
if (Error != null) {
uiUpdate.setText("Output : " + Error);
}else
{
//Show Response Json Onscreen(Activity)
uiUpdate.setText( Content );
/****************** Start Parse Response JSON Data *************/
String OutputData = "";
try {
JSONObject jsono = new JSONObject(Content);
JSONObject mainObject = jsono.getJSONObject("data");
JSONArray jsonArray = mainObject.getJSONArray("standing");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
// get details2 JSONObject
String position = object.optString("position").toString();
String team = object.optString("team").toString();
OutputData += "Position: " + position + " "
+ "Team Name : " + team + " ";
}
/****************** End Parse Response JSON Data *************/
//Show Parsed Output on screen (activity)
jsonParsed.setText( OutputData );
}catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
**I am Creating a premier league application which shows all the datas needed for a premier league fan. As Iam new to this I am getting confused over json parsing and getting data from apis. So Can anyone Explain to me how to change my code or Some links which would help me correct it.
Above given is my java code of Main Activity.**
Thank You Everyone for Helping out. But I found my answer from the search over the internet. Here I used VOLLEY to call the link.
JSON PARSER CLASS
public class ParseJSON {
public static String[] position1;
public static String[] team;
public static String[] points;
public static final String JSON_ARRAY = "data";
public static final String CHILD_ARRAY = "standings";
public static final String KEY_ID = "position";
public static final String KEY_NAME = "team";
private JSONObject users = null;
private JSONArray user2=null;
private JSONObject user3=null;
private String json;
public ParseJSON(String json){
this.json = json;
}
protected void parseJSON() {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(json);
users = jsonObject.getJSONObject(JSON_ARRAY);
try {
user2=users.getJSONArray(CHILD_ARRAY);
position1 = new String[user2.length()];
team = new String[user2.length()];
points=new String[user2.length()];
for (int i = 0; i < user2.length(); i++) {
JSONObject jo = user2.getJSONObject(i);
try {
user3=jo.getJSONObject("overall");
points[i] = user3.getString("points");
System.out.println("Message me: "+points[i]);
}catch (Exception e)
{
e.printStackTrace();
}
position1[i] = jo.getString(KEY_ID);
team[i] = jo.getString(KEY_NAME);
System.out.println("Message me: "+position1[i]);
System.out.println("Message me: "+team[i]);
}
}catch (Exception e)
{
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Main Activity Class
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final String JSON_URL="http://soccer.sportsopendata.net/v1/leagues/premier-league/seasons/16-17/standings";
private Button buttonGet;
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonGet = (Button) findViewById(R.id.buttonGet);
buttonGet.setOnClickListener(this);
listView = (ListView) findViewById(R.id.listView);
}
#Override
public void onClick(View v) {
sendRequest();
}
private void sendRequest() {
final StringRequest stringRequest = new StringRequest(JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String json){
ParseJSON pj = new ParseJSON(json);
pj.parseJSON();
CustomList cl = new CustomList(this, ParseJSON.position1,ParseJSON.team,ParseJSON.points);
listView.setAdapter(cl);
}
}
Custom Class for adding datas to list view
public class CustomList extends ArrayAdapter<String> {
private String[] position1;
private String[] team;
private String[] points;
private Activity context;
public CustomList(Activity context, String[] position1, String[] team, String[] points) {
super(context, R.layout.list_view_layout, position1);
this.context = context;
this.position1 = position1;
this.team = team;
this.points = points;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_view_layout, null, true);
TextView pos1 = (TextView) listViewItem.findViewById(R.id.position1);
TextView teamname = (TextView) listViewItem.findViewById(R.id.teamname);
TextView points1 = (TextView) listViewItem.findViewById(R.id.points);
pos1.setText("Position: "+position1[position]);
teamname.setText("Team: "+team[position]);
points1.setText("Points: "+points[position]);
return listViewItem;
}
}
Step 1 : Use Retroft + RxJava for Asynchronous API calls
Step 2 : Use Gson to Serialize and Deserialize.
Step 3 : Use json to POJO to have a Model Class
Simplify the code.

how do i insert selected option into database from givn 4-5 options by using spinner?

I am developing an app where on some page user need to select one option from given 4-5 options currently I'm using spinner for this functionality now the question is, if user selects 3rd or 4th option(only single option selection permitted) select how do i insert that particular option in mysql php database.following is the code I'm using right now..
//MainActivity.java
public class MainActivity_D extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
//Declaring an Spinner
private Spinner spinner2, spinner1;
private String str_spinner1, str_spinner2, s_name, s_course;
//An ArrayList for Spinner Items
private ArrayList<String> students1;
private ArrayList<String> students2;
Button mBtnSave;
//JSON Array
private JSONArray result1, result2, result;
//TextViews to display details
private TextView textViewName1;
private TextView textViewName2;
private TextView textViewCourse;
private TextView textViewSession;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainactivity_d);
//Initializing the ArrayList
students1 = new ArrayList<String>();
students2 = new ArrayList<String>();
//Initializing Spinner
//Adding an Item Selected Listener to our Spinner
//As we have implemented the class Spinner.OnItemSelectedListener to this class iteself we are passing this to setOnItemSelectedListener
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner2 = (Spinner) findViewById(R.id.spinner2);
spinner1.setOnItemSelectedListener(this);
spinner2.setOnItemSelectedListener(this);
mBtnSave = (Button) findViewById(R.id.button2);
mBtnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
submitForm();
}
});
//Initializing TextViews
textViewName1 = (TextView) findViewById(R.id.textViewName1);
textViewName2 = (TextView) findViewById(R.id.textViewName2);
// textViewCourse = (TextView) findViewById(R.id.textViewCourse);
// textViewSession = (TextView) findViewById(R.id.textViewSession);
//This method will fetch the data from the URL
getData1();
getData2();
}
private void submitForm() {
// Submit your form here. your form is valid
//Toast.makeText(this, "Submitting form...", Toast.LENGTH_LONG).show();
// s_name = spinner1.getSelectedItem().toString();
// s_course = spinner2.getSelectedItem().toString();
Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();
new InsertActivity(this).execute(s_name, s_course);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (parent.getId()){
case R.id.spinner1:
spinner1.setSelection(position);
s_name = (String) spinner1.getSelectedItem();
// getData1();
// showToast("Spinner1: position=" + position);
break;
case R.id.spinner2:
spinner2.setSelection(position);
s_course = (String) spinner2.getSelectedItem();
// getData2();
break;
}
/*if(spinner1.getId()==R.id.spinner1) {
textViewName1.setText(getName(position));
}
else if(spinner2.getId()==R.id.spinner2)
{
textViewName2.setText(getCourse(position));
}
switch (parent.getId()){
case R.id.spinner1:
// getData1();
// showToast("Spinner1: position=" + position);
break;
case R.id.spinner2:
// getData2();
break;
}*/
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
/* private String getName(int position){
String name="";
try {
//Getting object of given index
JSONObject json = result.getJSONObject(position);
//Fetching name from that object
name = json.getString(Config.TAG_NAME);
} catch (JSONException e) {
e.printStackTrace();
}
//Returning the name
return name;
}
private String getCourse(int position){
String course="";
try {
JSONObject json = result.getJSONObject(position);
course = json.getString(Config.TAG_COURSE);
} catch (JSONException e) {
e.printStackTrace();
}
return course;
}*/
private void getData1() {
//Creating a string request
StringRequest stringRequest1 = new StringRequest(Config.DATA_URL1,
new Response.Listener<String>() {
#Override
public void onResponse(String response1) {
JSONObject j1 = null;
try {
//Parsing the fetched Json String to JSON Object
j1 = new JSONObject(response1);
//Storing the Array of JSON String to our JSON Array
result1 = j1.getJSONArray(Config.JSON_ARRAY1);
//Calling method getStudents to get the students from the JSON Array
getStudents1(result1);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error1) {
}
});
//Creating a request queue
RequestQueue requestQueue1 = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue1.add(stringRequest1);
}
private void getStudents1(JSONArray j1) {
//Traversing through all the items in the json array
for (int i = 0; i < j1.length(); i++) {
try {
//Getting json object
JSONObject json1 = j1.getJSONObject(i);
//Adding the name of the student to array list
students1.add(json1.getString(Config.TAG_COURSE));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner1.setAdapter(new ArrayAdapter<String>(MainActivity_D.this, android.R.layout.simple_spinner_dropdown_item, students1));
}
//Initializing TextViews
// textViewCourse = (TextView) findViewById(R.id.textViewCourse);
// textViewSession = (TextView) findViewById(R.id.textViewSession);
//This method will fetch the data from the URL
private void getData2() {
//Creating a string request
StringRequest stringRequest2 = new StringRequest(Config.DATA_URL2,
new Response.Listener<String>() {
#Override
public void onResponse(String response2) {
JSONObject j2 = null;
try {
//Parsing the fetched Json String to JSON Object
j2 = new JSONObject(response2);
//Storing the Array of JSON String to our JSON Array
result = j2.getJSONArray(Config.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getStudents2(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error1) {
}
});
//Creating a request queue
RequestQueue requestQueue2 = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue2.add(stringRequest2);
}
private void getStudents2(JSONArray j2) {
//Traversing through all the items in the json array
for (int i = 0; i < j2.length(); i++) {
try {
//Getting json object
JSONObject json2 = j2.getJSONObject(i);
//Adding the name of the student to array list
students2.add(json2.getString(Config.TAG_USERNAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner2.setAdapter(new ArrayAdapter<String>(MainActivity_D.this, android.R.layout.simple_spinner_dropdown_item, students2));
}
}
//InsertActivity.java
public class InsertActivity extends AsyncTask<String, Void, String> {
private Context context;
Boolean error, success;
public InsertActivity(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String s_name = arg0[0];
// String userName = arg0[1];
String s_course = arg0[1];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?s_name=" + URLEncoder.encode(s_name, "UTF-8");
// data += "&username=" + URLEncoder.encode(userName, "UTF-8");
data += "&s_course=" + URLEncoder.encode(s_course, "UTF-8");
link = "http://insert_s1.php" + data;
// link = "http://example.com/mangoair10/tryrr.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
// return new String("Exception: " + e.getMessage());
// return null;
}
return null;
}
/* #Override
protected void onPostExecute(String result) {
String jsonStr = result;
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("success");
String message_result = jsonObj.getString("message");
if (query_result.equalsIgnoreCase("1")) {
Toast.makeText(context,message_result , Toast.LENGTH_LONG).show();
} else if (query_result.equalsIgnoreCase("-1")) {
Toast.makeText(context, message_result, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}*/
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("query_result");
Log.e("TAG", String.valueOf(query_result));
// String message_result = jsonObj.getString("message");
/* if (query_result.equals("SUCCESS")) {
Toast.makeText(context, "Insert", Toast.LENGTH_LONG).show();
} else if(query_result.equals("FAILURE")){
Toast.makeText(context, "Unable to Insert", Toast.LENGTH_LONG).show();
}*/
} catch (JSONException e) {
e.printStackTrace();
}
}
}
//Config.java
public class Config {
//JSON URL
// public static final String DATA_URL = "http://example.com/jsonphp1.php";
public static final String DATA_URL1 = "http://example.com/jsonphp2.php";
public static final String DATA_URL2 = "http://example.com/jsonphp1.php";
//Tags used in the JSON String
public static final String TAG_USERNAME = "username";
public static final String TAG_NAME = "name";
public static final String TAG_COURSE = "course";
public static final String TAG_SESSION = "session";
//JSON array name
public static final String JSON_ARRAY = "result";
public static final String JSON_ARRAY1 = "result1";
public static final String JSON_ARRAY2 = "result2";
}
//this is my php file
<?php
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
$s_name=$_POST['s_name'];
$s_course=$_POST['s_course'];
Sid=$_GET['id'];
$query = "UPDATE `students` SET s_name = '$s_name', s_course= '$s_course' WHERE id='$id'";
$inserted = mysqli_query($con, $query);
// echo $inserted;
if($inserted) {
echo '{"query_result":"SUCCESS"}';
}
else{
echo '{"query_result":"FAILURE"}';
}
mysqli_close($con);
?>
The error is self explanatory. You are getting an Integer in your response which cannot be converted to a JSONObject. Log your response and check if it is a valid JSON.
In your asyntask onPostExecute method print response like this and post your response then error will be detected
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
Log.e("TAG",jsonStr );
}

How to save spinner selected item in mysql db?

Here,I already fetched data from mysql db and this data shows into the spinner Now the problem is, I want to save spinner selected item into mysql database with different table, the item which i select from spinner it should save to database, how can i do this? By using php mysql i insert record into spinner and i want to update the records of register table with spinner selected item.Can i update the register table with spinner selected item values? please suggest me.
java file
public class MainActivity_d3 extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
//Declaring an Spinner
private Spinner spinner2, spinner1;
private String str_spinner1, str_spinner2, s_name, s_course;
//An ArrayList for Spinner Items
private ArrayList<String> students1;
private ArrayList<String> students2;
Button mBtnSave;
//JSON Array
private JSONArray result1, result2, result;
//TextViews to display details
private TextView textViewName1;
private TextView textViewName2;
private TextView textViewCourse;
private TextView textViewSession;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainactivity_d1);
//Initializing the ArrayList
students1 = new ArrayList<String>();
students2 = new ArrayList<String>();
//Initializing Spinner
//Adding an Item Selected Listener to our Spinner
//As we have implemented the class Spinner.OnItemSelectedListener to this class iteself we are passing this to setOnItemSelectedListener
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner2 = (Spinner) findViewById(R.id.spinner2);
spinner1.setOnItemSelectedListener(this);
spinner2.setOnItemSelectedListener(this);
mBtnSave = (Button) findViewById(R.id.button2);
mBtnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
submitForm();
}
});
//Initializing TextViews
textViewName1 = (TextView) findViewById(R.id.textViewName1);
textViewName2 = (TextView) findViewById(R.id.textViewName2);
// textViewCourse = (TextView) findViewById(R.id.textViewCourse);
// textViewSession = (TextView) findViewById(R.id.textViewSession);
//This method will fetch the data from the URL
getData1();
getData2();
}
private void submitForm() {
// Submit your form here. your form is valid
//Toast.makeText(this, "Submitting form...", Toast.LENGTH_LONG).show();
s_name = spinner1.getSelectedItem().toString();
s_course = spinner2.getSelectedItem().toString();
Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();
new InsertActivity(this).execute(s_name, s_course);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
/*if(spinner1.getId()==R.id.spinner1) {
textViewName1.setText(getName(position));
}
else if(spinner2.getId()==R.id.spinner2)
{
textViewName2.setText(getCourse(position));
}
/* switch (view.getId()){
case R.id.spinner1:
getData1();
break;
case R.id.spinner2:
getData2();
break;
}*/
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
/* private String getName(int position){
String name="";
try {
//Getting object of given index
JSONObject json = result.getJSONObject(position);
//Fetching name from that object
name = json.getString(Config.TAG_NAME);
} catch (JSONException e) {
e.printStackTrace();
}
//Returning the name
return name;
}
private String getCourse(int position){
String course="";
try {
JSONObject json = result.getJSONObject(position);
course = json.getString(Config.TAG_COURSE);
} catch (JSONException e) {
e.printStackTrace();
}
return course;
}*/
private void getData1() {
//Creating a string request
StringRequest stringRequest1 = new StringRequest(Config.DATA_URL1,
new Response.Listener<String>() {
#Override
public void onResponse(String response1) {
JSONObject j1 = null;
try {
//Parsing the fetched Json String to JSON Object
j1 = new JSONObject(response1);
//Storing the Array of JSON String to our JSON Array
result1 = j1.getJSONArray(Config.JSON_ARRAY1);
//Calling method getStudents to get the students from the JSON Array
getStudents1(result1);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error1) {
}
});
//Creating a request queue
RequestQueue requestQueue1 = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue1.add(stringRequest1);
}
private void getStudents1(JSONArray j1) {
//Traversing through all the items in the json array
for (int i = 0; i < j1.length(); i++) {
try {
//Getting json object
JSONObject json1 = j1.getJSONObject(i);
//Adding the name of the student to array list
students1.add(json1.getString(Config.TAG_COURSE));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner1.setAdapter(new ArrayAdapter<String>(MainActivity_d3.this, android.R.layout.simple_spinner_dropdown_item, students1));
}
//Initializing TextViews
// textViewCourse = (TextView) findViewById(R.id.textViewCourse);
// textViewSession = (TextView) findViewById(R.id.textViewSession);
//This method will fetch the data from the URL
private void getData2() {
//Creating a string request
StringRequest stringRequest2 = new StringRequest(Config.DATA_URL2,
new Response.Listener<String>() {
#Override
public void onResponse(String response2) {
JSONObject j2 = null;
try {
//Parsing the fetched Json String to JSON Object
j2 = new JSONObject(response2);
//Storing the Array of JSON String to our JSON Array
result = j2.getJSONArray(Config.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getStudents2(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error1) {
}
});
//Creating a request queue
RequestQueue requestQueue2 = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue2.add(stringRequest2);
}
private void getStudents2(JSONArray j2) {
//Traversing through all the items in the json array
for (int i = 0; i < j2.length(); i++) {
try {
//Getting json object
JSONObject json2 = j2.getJSONObject(i);
//Adding the name of the student to array list
students2.add(json2.getString(Config.TAG_USERNAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner2.setAdapter(new ArrayAdapter<String>(MainActivity_d3.this, android.R.layout.simple_spinner_dropdown_item, students2));
}
}
//InsertActivity
public class InsertActivity extends AsyncTask<String, Void, String> {
private Context context;
Boolean error, success;
public InsertActivity(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String s_name = arg0[0];
// String userName = arg0[1];
String s_course = arg0[1];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?s_name=" + URLEncoder.encode(s_name, "UTF-8");
// data += "&username=" + URLEncoder.encode(userName, "UTF-8");
data += "&s_course=" + URLEncoder.encode(s_course, "UTF-8");
link = "http://mangoair.in/Spinner/insert_s1.php" + data;
// link = "http://hostogen.com/mangoair10/tryrr.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
// return new String("Exception: " + e.getMessage());
// return null;
}
return null;
}
/* #Override
protected void onPostExecute(String result) {
String jsonStr = result;
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("success");
String message_result = jsonObj.getString("message");
if (query_result.equalsIgnoreCase("1")) {
Toast.makeText(context,message_result , Toast.LENGTH_LONG).show();
} else if (query_result.equalsIgnoreCase("-1")) {
Toast.makeText(context, message_result, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}*/
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("query_result");
if (query_result.equalsIgnoreCase("SUCCESS")) {
Toast.makeText(context, "Data inserted successfully. Signup successfully.", Toast.LENGTH_LONG).show();
} else if (query_result.equalsIgnoreCase("FAILURE")) {
Toast.makeText(context, "Data could not be inserted, fill all records.", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Get the value from the spinner as a string and just pass this string like a normal string

How to update listview after changing data in JSON?

Hello everyone and happy new year
I have JSON class where I retrieve some data that are retrieve from a database. The format of this JSON file is
{"people":[{"id":"15","first_name":"Theo","last_name":"Tziomakas","bio":"Hello from
Theo!!!","created":"2015-01-11 21:48:51"},
{"id":"16","first_name":"Jim","last_name":"Chytas","bio":"Hello from Chytas","created":"2015-01-11
21:53:42"}]}.
The idea is to retrieve the "first_name" and "second_name" in a listview. The "bio" should appear in another activity,but I don't know how to do that:(.
Here is my code.
public class MainActivity extends ActionBarActivity {
ListView list;
TextView fname;
TextView lname;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://xxxxxxx/tutorials/index.php";
//JSON Node Names
private static final String TAG_OS = "people";
private static final String TAG_FIRST_NAME = "first_name";
private static final String TAG_SECOND_NAME = "last_name";
//private static final String TAG_BIO = "bio";
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oslist = new ArrayList<HashMap<String, String>>();
new JSONParse().execute();
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
fname = (TextView)findViewById(R.id.first_name);
lname = (TextView)findViewById(R.id.last_name);
//abio = (TextView)findViewById(R.id.bio);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String first_name = c.getString(TAG_FIRST_NAME);
String last_name = c.getString(TAG_SECOND_NAME);
//String bio = c.getString(TAG_BIO);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_FIRST_NAME, first_name);
map.put(TAG_SECOND_NAME, last_name);
//map.put(TAG_BIO, bio);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_FIRST_NAME,TAG_SECOND_NAME }, new int[] {
R.id.first_name,R.id.last_name});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String bio = ((TextView) view.findViewById(R.id.bio))
.getText().toString();
switch (position) {
case 0:
Intent i = new Intent(MainActivity.this, SingleActivity.class);
i.putExtra("bio", bio);
startActivity(i);
break;
}
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
And finally I have the SecondActivity class,but nothing is shown when I click the first row of list.
public class SingleActivity extends ActionBarActivity {
TextView text;
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single);
text = (TextView)findViewById(R.id.text);
String bio = getIntent().getStringExtra("bio");
try {
JSONObject profileJSON = new JSONObject(bio);
android = profileJSON.getJSONArray(bio);
text.setText(""+android);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Thank you.
EDIT:The problem I had is fixed. Now I want to do something else. Let us suppose that we update the data in an existing row by changing "first_name,"last_name" and finally bio. It is done very easily in phpmyadmin tool. The problem is that the updated row is not shown in the listview. I have to reinstall the app in order to see it. Any ideas in that?
try this ,
replace onPostExecute with this
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
list=(ListView)findViewById(R.id.list);
// Getting JSON Array from URL
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String first_name = c.getString(TAG_FIRST_NAME);
String last_name = c.getString(TAG_SECOND_NAME);
//String bio = c.getString(TAG_BIO);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_FIRST_NAME, first_name);
map.put(TAG_SECOND_NAME, last_name);
map.put(TAG_BIO, bio);
oslist.add(map);
}
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_FIRST_NAME,TAG_SECOND_NAME }, new int[] {
R.id.first_name,R.id.last_name});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String bio =oslist.get(position).get(TAG_BIO);
// switch (position) {
// case 0:
Intent i = new Intent(MainActivity.this, SingleActivity.class);
i.putExtra("bio", bio);
startActivity(i);
break;
//}
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
and SingleActivity
text = (TextView)findViewById(R.id.text);
String bio = getIntent().getStringExtra("bio");
text.setText(bio );
Pay attention to what you put in the intent.
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String bio = ((TextView) view.findViewById(R.id.bio))
.getText().toString();
switch (position) {
case 0:
Intent i = new Intent(MainActivity.this, SingleActivity.class);
i.putExtra("bio", bio);
startActivity(i);
break;
}
}
notice that you take the text from a text view and add it to and intent.
When you retreive it use it as if its a json object.
If you want the bio string, you could put that in a variable, and then send it to an intent with just the string.
for example
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_FIRST_NAME,TAG_SECOND_NAME }, new int[] {
R.id.first_name,R.id.last_name});
list.setAdapter(adapter);
String bio = c.getString("bio");
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch (position) {
case 0:
Intent i = new Intent(MainActivity.this, SingleActivity.class);
i.putExtra("bio", bio);
startActivity(i);
break;
}
}
});
when retrieving it its easier to just do it with
public class SingleActivity extends ActionBarActivity {
TextView text;
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single);
text = (TextView)findViewById(R.id.text);
String bio = getIntent().getStringExtra("bio");
text.settext(bio)
}
}
now there is prob some bugs in these example, since i have not java or android sdk installed on my computer

Categories

Resources