I have two fragments, one shows a program list and one shows a course list. How do I get the selected program from the mainactivity to only show the corresponding course description? They match by ID. Currently, when I click on a program, the whole course list shows up instead of the corresponding course.
MainActivity Fragment (shows all data in JSON file):
ProgramAdapter programAdapter;
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
ProgramDetail item = (ProgramDetail) getListAdapter().getItem(position);
Intent intent = new Intent(getActivity(), ProgramDetailActivity.class);
intent.putExtra(ProgramDetailActivity.EXTRA_ID, item.getId());
startActivity(intent);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
programAdapter = new ProgramAdapter(getActivity());
setListAdapter(programAdapter);
setListShown(false);
new HttpAsyncTask().execute("https://gist.githubusercontent.com/kdotzenrod517/39bc7372759c762e33188fb1a6cbce5d/raw/a2baa28d19fd597be999c8fddb6b48c888cd33f4/gistfile1.txt");
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
Log.e("HttpAsyncTask", "doInBackground");
String result = "";
HttpURLConnection urlConnection = null;
try{
URL url = new URL(params[0]);
Log.e("HttpAsyncTask", params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Accept", "application/json");
InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
Log.e("HttpAsyncTask", "getInputStream");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String s = "";
while ((s = reader.readLine()) != null){
result += s;
Log.e("HttpAsyncTask", result);
}
} catch (Exception e){
Log.e("HttpAsyncTask", "EXCEPTION: " + e.getMessage());
} finally {
if (urlConnection != null){
urlConnection.disconnect();
}
}
return result;
}
#Override
protected void onPostExecute(String s) {
Log.e("HttpAsyncTask", "entering onPostExecute");
try {
JSONArray jsonArray = new JSONArray(s);
final int length = jsonArray.length();
Log.i("HttpAsyncTask", "Number" + length);
List<ProgramDetail> items = new ArrayList<>();
for (int i=0; i < length; i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
items.add(new ProgramDetail(jsonObject.getString("name"),null,jsonObject.getLong("id")));
}
programAdapter.addAll(items);
programAdapter.notifyDataSetChanged();
setListShown(true);
} catch (JSONException e) {
}
}
}
}
CourseList Fragment (should only show matching JSON data by ID)
`
protected void onPostExecute(String s) {
Log.e("HttpAsyncTask", "entering onPostExecute");
try {
JSONArray jsonArray = new JSONArray(s);
final int length = jsonArray.length();
Log.i("HttpAsyncTask", "Number" + length);
List<ProgramDetail> item = new ArrayList<>();
for (int i=0; i < length; i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
item.add(new ProgramDetail(jsonObject.getString("name"), null, jsonObject.getLong("id")));
}
programAdapter.addAll(item);
programAdapter.notifyDataSetChanged();
setListShown(true);
} catch (JSONException e) {
}
Program List
[
{
"id": "0",
"name": "Intro to Android"
},
{
"id": "1",
"name": "Advanced Android"
},
{
"id": "2",
"name": "Intro to Java"
},
{
"id": "3",
"name": "Advanced Java"
},
{
"id": "4",
"name": "Intro to Data Science"
}
]
Course List JSON
{
"id": "0",
"name": "Welcome to Android!"
},
{
"id": "1",
"name": "Enterprise level Android Dev"
},
{
"id": "2",
"name": "Welcome to Java!"
},
{
"id": "3",
"name": "Enterprise Level Java"
},
{
"id": "4",
"name": "Welcome to Data Science!"
}
Related
In my application I'm working with two spinners first spinner contains data like Department and id and second spinner contains deficiency and id, here I am working with some URL as below.
http://182.18.163.39/m/def.php?issue=1
This URL gives me first spinner values. On selecting a value from the first spinner the data related to that value will come in second spinner.
Here is my second URL which gives second spinner values.
"http://182.18.163.39/m/def.php?issue=2&dept="+dept_id
In this URL I want to pass the id from the first URL, here is my problem I am able to get all values from first spinner. When I select one value from first spinner it doesn't give me related values in the second spinner.
Anyone give me an example code for solving this.
Here is the code:
//Department spinner
Spinner spinner;
String URL="http://182.18.163.39/train/m/def.php?issue=1";
ArrayList<String> Department;
String uid;
//Deficiency category spinner
Spinner spinner2;
String URL2 = "http://182.18.163.39/train/m/def.php?issue=2&dept="+dept_id;
ArrayList<String>Deficiency;
String defid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_deficiency);
//spinner for department
Department = new ArrayList<>();
spinner=(Spinner)findViewById(R.id.select_department);
loadSpinnerData(URL);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String department = spinner.getItemAtPosition(spinner.getSelectedItemPosition()).toString();
Toast.makeText(getApplicationContext(),department,Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
// DO Nothing here
}
});
//spinner for deficiency
Deficiency = new ArrayList<>();
spinner2 = (Spinner)findViewById(R.id.deficiency_category);
loadSpinnerDeficiency(URL2);
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String deficiency = spinner2.getItemAtPosition(spinner2.getSelectedItemPosition()).toString();
Toast.makeText(getApplicationContext(),deficiency,Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
// DO Nothing here
}
});
}
private void loadSpinnerData(String url) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet(url);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity);
JSONArray jsonarray = new JSONArray(responseString);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String department = jsonobject.getString("Department");
dept_id = jsonobject.getString("ID");
Department.add(department);
}
spinner.setAdapter(new ArrayAdapter<String>(NewDeficiency.this, android.R.layout.simple_spinner_dropdown_item, Department));
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void loadSpinnerDeficiency(String url2) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet("http://182.18.163.39/train/m/def.php?issue=2&dept="+dept_id);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity);
JSONArray jsonarray = new JSONArray(responseString);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String defcat = jsonobject.getString("Deficiency");
defid = jsonobject.getString("ID");
Deficiency.add(defcat);
}
spinner2.setAdapter(new ArrayAdapter<String>(NewDeficiency.this, android.R.layout.simple_spinner_dropdown_item, Deficiency));
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
here is my json response of first URL:
[{
"Department": "Select Department",
"ID": ""
}, {
"Department": "Engg North",
"ID": "1"
}, {
"Department": "DIESEL SHED",
"ID": "2"
}, {
"Department": "S & T",
"ID": "3"
}, {
"Department": "SAFETY",
"ID": "4"
}, {
"Department": "Srdenwest",
"ID": "5"
}, {
"Department": "enggwest",
"ID": "6"
}, {
"Department": "Engg central",
"ID": "7"
}, {
"Department": "electmaint",
"ID": "8"
}, {
"Department": "Operating",
"ID": "9"
}, {
"Department": "Security",
"ID": "10"
}, {
"Department": "Diesel Shed",
"ID": "11"
}, {
"Department": "Electric Loco shed",
"ID": "12"
}, {
"Department": "C & W",
"ID": "13"
}, {
"Department": "trso",
"ID": "14"
}, {
"Department": "trdohe",
"ID": "15"
}, {
"Department": "engg",
"ID": "16"
}, {
"Department": "commercial",
"ID": "17"
}, {
"Department": "engg South",
"ID": "18"
}, {
"Department": "Mechanical",
"ID": "19"
}]
And here is my json response of second URL:
[{
"Deficiency": "Select Deficiency",
"ID": ""
}, {
"Deficiency": "Engg",
"ID": "1"
}, {
"Deficiency": "Track",
"ID": "25"
}, {
"Deficiency": "LCs",
"ID": "26"
}, {
"Deficiency": "Misc",
"ID": "43"
}, {
"Deficiency": "",
"ID": "NULL"
}]
you shuold create a custom object like
private HashMap<String,String>departmentMap=new HashMap<>();
private void loadSpinnerData(String url) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet(url);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity);
JSONArray jsonarray = new JSONArray(responseString);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String department = jsonobject.getString("Department");
uid = jsonobject.getString("ID");
Department.add(department);
departmentMap.put(department,uid);
}
spinner.setAdapter(new ArrayAdapter<String>(NewDeficiency.this, android.R.layout.simple_spinner_dropdown_item, Department));
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
and modify your firstSpinner onclick like
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l){
String department=spinner.getItemAtPosition(spinner.getSelectedItemPosition()).toString();
Toast.makeText(getApplicationContext(),department,Toast.LENGTH_LONG).show();
String id=departmentMap.get(department);
loadSpinnerDeficiency(URL2,id);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView){
// DO Nothing here
}
});
now you can use id in loadSpinnerDeficiency method to get proper response
private void loadSpinnerDeficiency(String url2,String uid) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet("http://182.18.163.39/train/m/def.php?issue=2&dept="+uid);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity);
JSONArray jsonarray = new JSONArray(responseString);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String defcat = jsonobject.getString("Deficiency");
defid = jsonobject.getString("ID");
Deficiency.add(defcat);
}
spinner2.setAdapter(new ArrayAdapter<String>(NewDeficiency.this, android.R.layout.simple_spinner_dropdown_item, Deficiency));
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I want to populate my spinner from wallet array from SQL database and then store the wallet id which is being selected by the user in the particular user details, not the wallet name. I have written this particular code and o have added the screenshot as well for the error.
Android Part
public class User extends AppCompatActivity {
ArrayAdapter<String> adapter;
ArrayList<Populate> listItems;
LinkedHashMap<String,String> walletId;
Button logout,editdetails;
SharedPreferences sp;
SharedPreferences.Editor editor;
public static final String DEFAULT = "N/A";
TextView usermail;
String email;
int id;
public static final int DEFAULTI = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
listItems = new ArrayList<>();
usermail = (TextView) findViewById(R.id.usermail);
editdetails = (Button) findViewById(R.id.editdetails);
logout = (Button) findViewById(R.id.logout);
sp = getSharedPreferences("Login", Context.MODE_PRIVATE);
email = sp.getString("email", DEFAULT);
usermail.setText("Welcome " + email);
id = sp.getInt("id",DEFAULTI);
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/** pref = getSharedPreferences("Login", Context.MODE_PRIVATE);
editor = pref.edit();
editor.putBoolean("loginfirst",false);
editor.commit();**/
Intent i = new Intent(User.this, Login.class);
startActivity(i);
finish();
}
});
}
public void onEdit(View v){
BackgroundTask backgroundTask = new BackgroundTask();
backgroundTask.execute(String.valueOf(id));
}
class BackgroundTask extends AsyncTask<String, Void, String> {
ArrayList<Populate> list;
String add_info_url;
#Override
protected void onPreExecute() {
list=new ArrayList<>();
add_info_url = "http://192.168.2.6/Deal%20Engine/editdetails.php";
}
#Override
protected void onPostExecute(String result) {
listItems.addAll(list);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
//SharedPreferences sp = getSharedPreferences("Login",Context.MODE_PRIVATE);
Intent i = new Intent(User.this, EditDetails.class);
startActivity(i);
}
#Override
protected String doInBackground(String... args) {
BufferedReader reader = null;
try {
URL url = new URL(add_info_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String dataString = URLEncoder.encode("id", "UTF-8") + "=" + URLEncoder.encode(String.valueOf(id), "UTF-8");
Log.d("id", String.valueOf(id));
bufferedWriter.write(dataString);
Log.d("Result", dataString);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
Log.d("String", finalJson);
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("user");
StringBuffer finalBufferedData = new StringBuffer();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
int status_code = finalObject.getInt("status_code");
String status_desc = finalObject.getString("status_desc");
String user_id = finalObject.getString("user_id");
int id = finalObject.getInt("id");
String name=finalObject.getString("name");
String pass= finalObject.getString("pass");
String location = finalObject.getString("location");
String cards=finalObject.getString("cards");
String category= finalObject.getString("category");
String wallet = finalObject.getString("wallet");
String operator=finalObject.getString("operator");
String loyaltyProgram= finalObject.getString("loyaltyProgram");
String membership= finalObject.getString("membership");
JSONObject walletArrayObject = new JSONObject(finalObject.getString("wallet_array"));
JSONArray walletArray = walletArrayObject.getJSONArray("wallets");
Log.d("Arraysize",String.valueOf(walletArray));
for(int j =0;j<walletArray.length();j++)
{
JSONObject walletObject = walletArray.getJSONObject(j);
list.add(new Populate(String.valueOf(walletObject.getInt("id")),walletObject.getString("wallet_name")));
}
sp = getSharedPreferences("Login",Context.MODE_PRIVATE);
editor=sp.edit();
editor.putString("name",name);
editor.putString("pass",pass);
editor.putInt("id",id);
editor.putString("location",location);
editor.putString("cards",cards);
editor.putString("category",category);
editor.putString("wallet",wallet);
editor.putString("operator",operator);
editor.putString("wallets",String.valueOf(list));
editor.putString("loyaltyProgram",loyaltyProgram);
editor.putString("membership",membership);
editor.commit();
finalBufferedData.append(status_code + " - " + status_desc + " -" + user_id + " -"+id + " -"+name+ " -"+list +"\n");
}
inputStream.close();
httpURLConnection.disconnect();
Log.d("Result", dataString);
return finalBufferedData.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
}
error I am getting
06-29 12:53:08.015 28974-28988/com.example.tanmayjain.twowaycommunication D/String: {"user":[{"status_code":"1","status_desc":"Success","user_id":"482","id":"26","name":"tanmay ","pass":"a006b22f887f7d922bafa4c8186ccafd","location":"Ahmedabad","cards":"ICICI Bank","category":"Platinum","wallet":"","operator":"Vodafone","loyaltyProgram":"Any","membership":"All Time","wallet_array":"{\"wallets\":[{\"1\":[\"Paytm\"],\"2\":[\"Freecharge\"],\"3\":[\"Mobikwik\"],\"4\":[\"PayUmoney\"],\"5\":[\"CitrusCash\"],\"6\":[\"Airtel Money\"],\"7\":[\"Oxigen Wallet\"],\"8\":[\"OLAMoney\"],\"9\":[\"HDFC PayZapp\"],\"10\":[\"Chillr by HDFC\"],\"11\":[\"Pockets by ICICI bank\"],\"12\":[\"JioMoney\"],\"13\":[\"SBI Buddy\"],\"14\":[\"mRupee\"],\"15\":[\"Itzcash\"]}]}"}]}
06-29 12:53:08.015 28974-28988/com.example.tanmayjain.twowaycommunication D/Arraysize: [{"1":["Paytm"],"2":["Freecharge"],"3":["Mobikwik"],"4":["PayUmoney"],"5":["CitrusCash"],"6":["Airtel Money"],"7":["Oxigen Wallet"],"8":["OLAMoney"],"9":["HDFC PayZapp"],"10":["Chillr by HDFC"],"11":["Pockets by ICICI bank"],"12":["JioMoney"],"13":["SBI Buddy"],"14":["mRupee"],"15":["Itzcash"]}]
06-29 12:53:08.016 28974-28988/com.example.tanmayjain.twowaycommunication W/System.err: org.json.JSONException: No value for id
06-29 12:53:08.016 28974-28988/com.example.tanmayjain.twowaycommunication W/System.err: at org.json.JSONObject.get(JSONObject.java:389)
06-29 12:53:08.016 28974-28988/com.example.tanmayjain.twowaycommunication W/System.err: at org.json.JSONObject.getInt(JSONObject.java:478)
06-29 12:53:08.016 28974-28988/com.example.tanmayjain.twowaycommunication W/System.err: at com.example.tanmayjain.twowaycommunication.User$BackgroundTask.doInBackground(User.java:167)
06-29 12:53:08.017 28974-28988/com.example.tanmayjain.twowaycommunication W/System.err: at com.example.tanmayjain.twowaycommunication.User$BackgroundTask.doInBackground(User.java:85)
06-29 12:53:08.017 28974-28988/com.example.tanmayjain.twowaycommunication W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:295)
I want to fetch id and wallet name from the array displayed in array size but i am getting this error.
Your json is wrong, because your walletObject contains this:
{
"wallets": [{
"1": ["Paytm"],
"2": ["Freecharge"],
"3": ["Mobikwik"],
"4": ["PayUmoney"],
"5": ["CitrusCash"],
"6": ["Airtel Money"],
"7": ["Oxigen Wallet"],
"8": ["OLAMoney"],
"9": ["HDFC PayZapp"],
"10": ["Chillr by HDFC"],
"11": ["Pockets by ICICI bank"],
"12": ["JioMoney"],
"13": ["SBI Buddy"],
"14": ["mRupee"],
"15": ["Itzcash"]
}]
}
You got the error because you would like to get the value of id property, but your json doesn't contains id field.
Your json has more problems:
1. send an object instead of array (wallet_array)
2. change your wallet object structure
I think you should use this json structure:
{
"user": [{
"status_code": "1",
"status_desc": "Success",
"user_id": "482",
"id": "26",
"name": "tanmay ",
"pass": "a006b22f887f7d922bafa4c8186ccafd",
"location": "Ahmedabad",
"cards": "ICICI Bank",
"category": "Platinum",
"wallet": "",
"operator": "Vodafone",
"loyaltyProgram": "Any",
"membership": "All Time",
"wallet_array": [{
"id": 1,
"name": "Paytm"
},
{
"id": 2,
"name": "Freecharge"
},
{
"id": 3,
"name": "Mobikwik"
},
{
"id": 4,
"name": "PayUmoney"
},
{
"id": 5,
"name": "CitrusCash"
},
{
"id": 6,
"name": "Airtel Money"
},
{
"id": 7,
"name": "Oxigen Wallet"
},
{
"id": 8,
"name": "OLAMoney"
},
{
"id": 9,
"name": "HDFC PayZapp"
}
]
}]
}
While fetching data in TextView I am getting an error. I tried but its not working.
Error parsing data org.json.JSONException: End of input at character 0
Json
[{
"0": "1",
"cl_id": "1",
"1": "",
"cl_department": "",
"2": "3G COMMUNICATION",
"cl_pname": "3G COMMUNICATION",
"3": "NIRAJBHAI",
"cl_salesperson": "NIRAJBHAI",
"4": "",
"cl_oname": "",
"5": "MOHMADBHAI",
"cl_contact": "MOHMADBHAI",
"6": "JUBELY SHAK MARKET",
"cl_address": "JUBELY SHAK MARKET",
"7": "",
"cl_city": "",
"8": "360001",
"cl_pincode": "360001",
"9": "",
"cl_bdate": "",
"10": "",
"cl_adate": "",
"11": "",
"cl_opening": "",
"12": "9376052000",
"cl_cnumber": "9376052000",
"13": "",
"cl_wnumber": "",
"14": "",
"cl_email": "",
"15": "RT40848",
"cl_wodcode": "RT40848",
"16": "",
"cl_active": "",
"17": "",
"cl_saleman": "",
"18": "",
"cl_bank_name": "",
"19": "",
"cl_bank_city": "",
"20": "",
"cl_ifsc_code": "",
"21": "",
"cl_bank_ac_no": "",
"22": "",
"cl_bank_ac_holder": "",
"23": "",
"cl_pancard_no": "",
"24": "",
"cl_visiting_card": "",
"25": "ACTIVE",
"cl_status": "ACTIVE",
"26": "",
"cl_aread": "",
"27": "",
"cl_target": "",
"28": "",
"cl_archive": "",
"29": "",
"cl_remaining": "",
"30": "A1",
"cl_group": "A1",
"31": "Om",
"cl_category": "Om",
"32": "",
"cl_credit": ""
},
Here is my complete code,
Main.java
public class MainActivity extends Activity {
private WebView wv1;
InputStream is=null;
String result=null;
String line=null;
JSONObject jsonobject;
public static String DATA_URL = "http://10.0.2.2/portal/fetchwod.php";
JSONParser jParser = new JSONParser();
JSONArray ownerObj;
ArrayList<HashMap<String, String>> arraylist;
ArrayList<String> delivery_fetch = new ArrayList<String>();
String suid,uid,wt_wod_code1,wt_party1;
TextView abcd,abc1;
View view;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DownloadJSON().execute();
abcd =(TextView)findViewById(R.id.abc);
abc1 =(TextView)findViewById(R.id.abc1);
}
private class MyBrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url ) {
view.loadUrl(url);
String id = abcd.getText().toString().trim();
return true;
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/portal/autocomplete.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("Pass 1", "connection success ");
} catch (Exception e) {
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address", Toast.LENGTH_LONG).show();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("Pass 2", "connection success ");
} catch (Exception e) {
Log.e("Fail 2", e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void args) {
try {
JSONArray JA = new JSONArray(result);
JSONObject json = null;
final String[] str1 = new String[JA.length()];
for (int i = 0; i < JA.length(); i++) {
json = JA.getJSONObject(i);
str1[i] = json.getString("cl_pname");
}
final AutoCompleteTextView text = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
final List<String> list = new ArrayList<String>();
for (int i = 0; i < str1.length; i++) {
list.add(str1[i]);
}
Collections.sort(list);
final ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.my_list_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_list_item_1);
text.setThreshold(1);
text.setAdapter(dataAdapter);
text.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
wv1 = (WebView) findViewById(R.id.webView);
wv1.setWebViewClient(new MyBrowser());
wv1.loadUrl("http://10.0.2.2/portal/on_target.php?=cod");
wv1.getSettings().setLoadsImagesAutomatically(true);
wv1.getSettings().setJavaScriptEnabled(true);
wv1.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
Toast.makeText(getApplicationContext(), (CharSequence) arg0.getItemAtPosition(arg2), Toast.LENGTH_LONG).show();
wt_wod_code1 = text.getText().toString();
wt_party1 = text.getText().toString();
abcd.setText(text.getText());
Log.d("wt_wod_code", wt_party1);
new getdata().execute();
}
});
} catch (Exception e) {
Log.e("Fail 3", e.toString());
}
}
}
private class getdata extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
try {
String uid = abcd.getText().toString().trim();
arraylist = new ArrayList<HashMap<String, String>>();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("cl_pname", uid));
JSONObject json = jParser.makeHttpRequest(DATA_URL, "GET", params);
int success1 = Integer.parseInt(json.getString("success4"));
Log.d("success4", json.toString());
if (success1 == 0) {
Snackbar.make(view, "Not Data Found", Snackbar.LENGTH_LONG).show();
}
if (success1 == 1) {
ownerObj = json.getJSONArray("Ordera");
for (int i = 0; i < ownerObj.length(); i++) {
jsonobject = ownerObj.getJSONObject(i);
delivery_fetch.add(jsonobject.getString("cl_wodcode"));
}
}
}
catch(Exception e)
{
}
return null;
}
#Override
protected void onPostExecute(Void args) {
abc1 =(TextView)findViewById(R.id.abc1);
abc1.setText(delivery_fetch.toString());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Here is my Logcat,
com.example.sachin.addvisit E/Pass 1: connection success
com.example.sachin.addvisit E/Pass 2: connection success
com.example.sachin.addvisit D/wt_wod_code: D.K. METAL
com.example.sachin.addvisit D/response: {"success":1,"Ordera":[{"cl_wodcode":"RT34705","cl_pname":"D.K. METAL"}]}
com.example.sachin.addvisit E/Buffer Error: Error converting result java.lang.NullPointerException: lock == null
com.example.sachin.addvisit E/JSON Parser: Error parsing data org.json.JSONException: End of input at character 0 of
The data is displaying in the logcat but not fetching in the TextView.
I validated my JSON online an it looks alright.
i don't know where's the problem is please help me out.
if required i'll post my API too..
Parse the JSON as follows,
final String[] str1 = new String[JA.length()];
final String[] str2 = new String[JA.length()];
for (int i = 0; i < JA.length(); i++) {
json = JA.getJSONObject(i);
str1[i] = json.getString("cl_pname");
str2[i] = json.getString("cl_wodcode");
}
Inside the OnItemClickListener,
text.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selected_cl_pname = (String) parent.getItemAtPosition(position);
int index = Arrays.asList(str1).indexOf(selected_cl_pname);
String selected_cl_wodcode = str2[index];
abc1.setText(selected_cl_wodcode);
// rest of your code
}
});
I recommend to use a model class and use GSON to parse the JSON.
I'm trying to read data from this API: http://events.makeable.dk/api/getEvents with the AsyncTask method which Is first time I try this. I'm trying to only read all TITLES from the API, but I'm not getting any titles.
Instead I get this exception: W/System.err: org.json.JSONException: (...)
Which shows me the whole API.
I have put Log.d(); around my code and I can se that my code never do or reach something in onPostExecute(String s) and thats is maybe why I never get any TITLES.
The many examples on the web of how to do this is so different from eachother and makes this very frustrating to solve!
private class JsonParser extends AsyncTask<String, Void, String> {
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(MainActivity.this, "LOADING DATA FROM API", Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(String... params) {
try{
url = new URL(URL);
conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setDoOutput(true);
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
InputStream inputStream = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine())!= null){
result.append(line);
}
return (result.toString());
}
}catch (MalformedURLException e){
e.printStackTrace();
}catch (Exception ee){
ee.printStackTrace();
}
return "";
}
#Override
protected void onPostExecute(String s) {
//------ never comes below this area //-----------
try{
JSONArray jsonArray = new JSONArray(s);
for(int i =0; i<jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.d("TAG", "JSON: " + jsonObject.getString("TITLE"));
}
}catch (Exception e){
e.printStackTrace();
}
}
}
I viewed your API's response at this Website. It is a JSON Object because it is started by an open curly brace {. So therefore use JSONObject first.
The response looks like this:
{
"success": true,
"message": "548 events returned successfully",
"last_change": 1459515263,
"events": [
{
"category": "Musik",
"category_id": "75",
"datelist": [
{
"start": 1436536800,
"end": 1436544000
}
],
"description": "",
"description_english": "",
"description_german": "",
"eventgroup": "",
"eventid": "55815f7fe714a",
"family_friendly": "0",
"last_updated": 1436166668,
"location_address": "Klostertorv 1",
"location_city": "Århus C",
"location_id": "1593",
"location_latitude": 56.158092,
"location_longitude": 10.206756,
"location_name": "Klostertorv",
"location_postcode": "8000",
"organizer_email": "",
"organizer_name": "Café Smagløs ",
"organizer_phone": "",
"picture_name": "http://www.jazzfest.dk/img/photos_big/tcha-badjo---strings-og-buttons.jpg",
"price": "-1",
"subcategory": "Musik",
"subcategory_id": "84",
"subtitle": "",
"subtitle_english": "",
"subtitle_german": "",
"tags": "Swing/Mainstream",
"tickets_url": "",
"title": "Tcha Badjo + Strings & Buttons KONCERT AFLYST",
"title_english": "Tcha Badjo + Strings & Buttons CONCERT CANCELLED",
"title_german": "Tcha Badjo + Strings & Buttons CONCERT CANCELLED",
"url": "http://www.jazzfest.dk/?a=reviews&lang=&kryds_id=2122&y=2015",
"user_id": "23",
"video_url": ""
}]
}
So therefore it is:
try {
JSONObject object = new JSONObject(s);
JSONArray events = object.getJSONArray("events");
int evSize = events.length();
for (int x = 0; x < evSize; x++) {
JSONObject object1 = events.getJSONObject(x);
String title = object1.getString("title");
}
} catch (JSONException e) {
e.printStackTrace();
}
I got the json data using this
``
private void loadQuestions() throws Exception {
try {
InputStream questions = this.getBaseContext().getResources()
.openRawResource(R.raw.questions);
bReader = new BufferedReader(new InputStreamReader(questions));
StringBuilder quesString = new StringBuilder();
String aJsonLine = null;
while ((aJsonLine = bReader.readLine()) != null) {
quesString.append(aJsonLine);
}
Log.d(this.getClass().toString(), quesString.toString());
JSONObject quesObj = new JSONObject(quesString.toString());
quesList = quesObj.getJSONArray("Questions");
Log.d(this.getClass().getName(),
"Num Questions " + quesList.length());
} catch (Exception e){
} finally {
try {
bReader.close();
} catch (Exception e) {
Log.e("", e.getMessage().toString(), e.getCause());
}
}
}
public static JSONArray getQuesList() {
return quesList;
}
``
Here is the json data.
``
{
"Questions": [
{
"Question": "Which animal is Carnivorous?",
"CorrectAnswer": 1,
"Answers": [
{
"Answer": "Cow"
},
{
"Answer": "Lion"
},
{
"Answer": "Goat"
},
{
"Answer": "Elephant"
}
]
},
{
"Question": "Humans need",
"CorrectAnswer": 0,
"Answers": [
{
"Answer": "Oxygen"
},
{
"Answer": "Nitrogen"
},
{
"Answer": "CarbonDioxide"
},
{
"Answer": "Hydrogen"
}
]
},
{
"Question": "Choose the Amphibian ",
"CorrectAnswer": 0,
"Answers": [
{
"Answer": "Frog"
},
{
"Answer": "Owl"
},
{
"Answer": "Goat"
},
{
"Answer": "Fox"
}
]
},
{
"Question": "---- is part of Earth`s Atmosphere.",
"CorrectAnswer": 1,
"Answers": [
{
"Answer": "Unisphere"
},
{
"Answer": "Troposphere"
},
{
"Answer": "Oxysphere"
},
{
"Answer": "Carbosphere"
}
]
},
]
}
After getting the json data
All I need now is to randomize it.
Help a brother please, I have tried everything but nothing is working
Thanks in advance
After
quesList = quesObj.getJSONArray("Questions"); // Right place to shuffle PeterOla,add this to randomize questions list:
List<JSONObject> questionsList = new ArrayList<JSONObject>(quesList.length());
for(int i=0,size=quesList.length();i<size;++i){
try {
questionsList.add(quesList.getJSONObject(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
long seed = System.nanoTime();
Collections.shuffle(questionsList, new Random(seed));
Put values into a list, then you can shuffle it easily. Use this:
ArrayList<String> listdata = new ArrayList<String>();
JSONArray jArray = (JSONArray)jsonObject;
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.get(i).toString());
}
}
Collections.shuffle(listdata);
try {
JSONObject jsonObject = new JSONObject(response);
String current_page = jsonObject.optString("current_page");
NextPageUrl = jsonObject.optString("next_page_url");
if (current_page.equals("1")){
lifeHomeModels.clear();
JSONArray data = jsonObject.getJSONArray("data");
for (int i =0;i<data.length();i++){
JSONObject jsonObject1 = data.getJSONObject(i);
String id = jsonObject1.optString("id");
String post_user_id = jsonObject1.optString("user_id");
String post_id = jsonObject1.optString("post_id");
String post_details = jsonObject1.optString("post_details");
}
Family_HomeModel inputModel = new Family_HomeModel();
inputModel.setId(id);
inputModel.setPost_user_id(post_user_id);
inputModel.setPost_id(post_id);
inputModel.setPost_details(post_details);
lifeHomeModels.add(inputModel);
}
long seed = System.nanoTime();
Collections.shuffle(lifeHomeModels, new Random(seed));
}
lifeHomeAdapter.notifyDataSetChanged();
}
catch (JSONException e) {
e.printStackTrace();
}