How to fetch a data from the database mysql using asynctask? - android

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.

Related

How to get marathi data from web service which is in .net to spinner?

I am trying it for just another text with yesterdays answers
Just taken one text view and in on create only tried to apply custom font
And the output still not getting Output is like this
current output
See code below
Its showing like this in emulator
{"Get_DepoScheme": [{
"Flag": 1,
"Msg": "Success",
"SchemeId": 1,
"SchemeName": "मुदत ठेव",
"Glid": 55
}, {
"Flag": 1,
"Msg": "Success",
"SchemeId": 2,
"SchemeName": "कर्मचारी भ.नि.नि.मुदत ठेव",
"Glid": 38
}, {
"Flag": 1,
"Msg": "Success",
"SchemeId": 3,
"SchemeName": "सभासद कायम ठेव",
"Glid": 14
}, {
"Flag": 1,
"Msg": "Success",
"SchemeId": 5,
"SchemeName": "आवर्ती ठेव (आर.डी.)",
"Glid": 51
}, {
"Flag": 1,
"Msg": "Success",
"SchemeId": 6,
"SchemeName": "सुकन्या ठेव योजना",
"Glid": 77
}, {
"Flag": 1,
"Msg": "Success",
"SchemeId": 7,
"SchemeName": "स्वामी पेन्शन ठेव योजना",
"Glid": 78
}, {
"Flag": 1,
"Msg": "Success",
"SchemeId": 16,
"SchemeName": "दामदुप्पट ठेव",
"Glid": 54
}]
}
try URLDecoder, for example try this
String flag = URLDecoder.decode(json_data.getString("Flag"), "UTF-8");
and set the text to textview like this
TextView tv = (TextView) findViewById(R.id.tv);
Typeface marathi = Typeface.createFromAsset(getAssets(), "akshar.ttf");
tv.setTypeface(marathi);
tv.setText(flag);
Download the marathi font from here and create an asset folder in your project and add it there.(assets location app>src>main>assets>akshar.ttf)
output ->>
used AsyncTask :
public class TestMarathiData extends ActionBarActivity
{
InputStream is = null;
String result = null,Uname;
String line = null;
ArrayAdapter<String> adapter;
ArrayList list1;
boolean isInternetConn;
Button btn1;
TelephonyManager tel;
String IMEI;
ProgressDialog progressDialog ;
String GetSchemePath="URL here";
HttpURLConnection httpURLConnection ;
URL url;
OutputStream outputStream;
BufferedWriter bufferedWriter ;
int RC ;
BufferedReader bufferedReader ;
StringBuilder stringBuilder;
boolean check = true;
TextView txtv_scheme;
Spinner SpinnerScheme;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_marathi_data);
///// HTTP code ////
if (Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
//
/////// to get IMEI number ///////
tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
IMEI = tel.getDeviceId().toString();
//
//Global Variables
final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
//
Uname = globalVariable.getUID();
list1=new ArrayList<String>();
txtv_scheme = (TextView)findViewById(R.id.txtv_scheme);
btn1 = (Button)findViewById(R.id.btn1);
SpinnerScheme = (Spinner)findViewById(R.id.SpinnerScheme);
btn1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
GetDepositScheme();
}
});
}//EOF OnCreate
//GetDepositScheme
private void GetDepositScheme()
{
class AsyncTaskGetScheme extends AsyncTask<Void,Void,String>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = ProgressDialog.show(TestMarathiData.this,"Fetching Data","Please Wait",false,false);
}
#Override
protected void onPostExecute(String string1)
{
super.onPostExecute(string1);
try
{
JSONObject json = new JSONObject(result);
JSONArray jArray = json.getJSONArray("Get_DepoScheme");
List<String> l = new ArrayList<String>();
for (int i = 0; i < jArray.length(); i++)
{
JSONObject json_data = jArray.getJSONObject(i);
String SchemeId = json_data.getString("SchemeId");
String SchemeName = json_data.getString("SchemeName");
//
l.add(SchemeId+"-"+SchemeName);
//
adapter = new ArrayAdapter<String>(TestMarathiData.this,R.layout.spinner_item,l)
{
public View getView(int position, View convertView, ViewGroup parent)
{
View v = super.getView(position, convertView, parent);
Typeface externalFont = Typeface.createFromAsset(getAssets(), "fonts/ARIALUNI.TTF");
((TextView) v).setTypeface(externalFont);
return v;
}
public View getDropDownView(int position, View convertView, ViewGroup parent)
{
View v = super.getDropDownView(position, convertView, parent);
Typeface externalFont = Typeface.createFromAsset(getAssets(), "fonts/akshar.ttf");
((TextView) v).setTypeface(externalFont);
v.setBackgroundColor(Color.WHITE);
return v;
}
};
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
SpinnerScheme.setAdapter(adapter);
} // for
progressDialog.dismiss();
SpinnerScheme.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3)
{
String Spinner_item = SpinnerScheme.getSelectedItem().toString();
Toast.makeText(getApplicationContext(), "Selected :: " + Spinner_item, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0)
{}
});//
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_SHORT).show();
}
}
#Override
protected String doInBackground(Void... params)
{
GetSchemeClass getschemeClass = new GetSchemeClass();
HashMap<String,String> HashMapParams = new HashMap<String,String>();
HashMapParams.put("Username",Uname);
String FinalData = getschemeClass.GetSchemeHttpRequest(GetSchemePath,HashMapParams);
return FinalData;
}
}
AsyncTaskGetScheme AsyncTaskGetSchemeOBJ = new AsyncTaskGetScheme();
AsyncTaskGetSchemeOBJ.execute();
}//EOF GetDepositScheme
//GetSchemeClass
private class GetSchemeClass
{
public String GetSchemeHttpRequest(String requestURL, HashMap<String, String> PData)
{
StringBuilder stringBuilder = new StringBuilder();
try
{
url = new URL(requestURL);
httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setReadTimeout(20000);
httpURLConnection.setConnectTimeout(20000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
outputStream = httpURLConnection.getOutputStream();
bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
bufferedWriter.write(bufferedWriterDataFN(PData));
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
RC = httpURLConnection.getResponseCode();
if (RC == HttpsURLConnection.HTTP_OK)
{
bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
stringBuilder = new StringBuilder();
String RC2;
while ((RC2 = bufferedReader.readLine()) != null)
{
stringBuilder.append(RC2);
}
}
result = stringBuilder.toString();
Log.d("Result", "Result" + result);
}
catch (Exception e)
{
e.printStackTrace();
}
return stringBuilder.toString();
}
private String bufferedWriterDataFN(HashMap<String, String> HashMapParams) throws UnsupportedEncodingException
{
stringBuilder = new StringBuilder();
for (Map.Entry<String, String> KEY : HashMapParams.entrySet())
{
if (check)
check = false;
else
stringBuilder.append("&");
stringBuilder.append(URLEncoder.encode(KEY.getKey(), "UTF-8"));
stringBuilder.append("=");
stringBuilder.append(URLEncoder.encode(KEY.getValue(), "UTF-8"));
}
return stringBuilder.toString();
}
}//EOF GetSchemeClass
}//EOF Main

How to parse Json Array and Json Object having two keys and values in android?

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"
}
]
}]
}

Trying to get a single json object android

Would really apreciate if someone can help me out here. Trying to get "full_name", "Sex" and "location" if "full_name" is "John" but not working
public class DataParser extends AsyncTask<Void,Void,Integer>{
Context c;
ListView lv;
String jsonData;
ProgressDialog pd;
ArrayList<Person> persons=new ArrayList<>();
public DataParser(Context c, ListView lv, String jsonData) {
this.c = c;
this.lv = lv;
this.jsonData = jsonData;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd=new ProgressDialog(c);
pd.setTitle("Parse");
pd.setMessage("Parsing...Please wait");
pd.show();
}
#Override
protected Integer doInBackground(Void... params) {
return this.parseData();
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
pd.dismiss();
if(result==0)
{
Toast.makeText(c,"Unable to parse",Toast.LENGTH_SHORT).show();
}else {
//CALL ADAPTER TO BIND DATA
CustomAdapter adapter=new CustomAdapter(c,persons);
lv.setAdapter(adapter);
}
}
private int parseData()
{
try {
JSONObject ja= new JSONObject(jsonData);
persons.clear();
Person s=null;
JSONObject jo=ja.getJSONObject("full_name");
if (jo.equals("John")) {
int id = jo.getInt("id");
String name = jo.getString("full_name");
String sex = jo.getString("sex");
String location = jo.getString("location");
s = new Person();
s.setId(id);
s.setFull_name(name);
s.setSex(sex);
s.setLocation(location);
persons.add(s);
}
return 1;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
}
Would really apreciate if someone can help me out here. Trying to get "full_name", "Sex" and "location" if "full_name" is "John" but not working
I'm going to guess that you have a JSONArray of person and you want to get the object that has person = John.
If the data is like this
[{
"full_name": "John Smith",
"sex": "male",
"location": "New York, NY, United States"
}, {
"full_name": "Angela Johnson",
"sex": "female",
"location": "San Diego, CA, United States"
}]
You can write:
JSONArray people = new JSONArray(jsondata);
int index = 0;
for (int i = 0; i < people.length(); i++) {
JSONObject tmpObj = people.getJSONObject(i);
string name = tmpObj.getString("full_name");
if (name == "John") {
index = i;
break;
}
}
JSONObject johnObjExample = people.getJSONObject(index);
string johnName = johnObjExample.getString("full_name");
int id = johnObjExample.getInt("id");
String name = johnObjExample.getString("full_name");
String sex = johnObjExample.getString("sex");
String location = johnObjExample.getString("location");

How do I match data by ID's in Android using JSON?

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!"
}

my json get only single value from json file

below is my json code but it return only single value from json file i am getting only single Friday from json file but actually in json file there is 4 Fridays how do i get all values of Friday ?
when i run my code ListView only show this Friday value "dish_name":"Hamburger", how i get all four values of Friday
{
"status": 1,
"data": [{
"school_name": "LittleStar ",
"calendar_id": "1",
"menu_title": "Atypical Menu",
"dish_name": "Mandarin Chicken Rice Bowl",
"dish_id": "210",
"day": "Fri",
"Schedule": "weekly"
}, {
"school_name": "LittleStar ",
"calendar_id": "1",
"menu_title": "Atypical Menu",
"dish_name": "Chicken Burger",
"dish_id": "206",
"day": "Fri",
"Schedule": "weekly"
}, {
"school_name": "LittleStar ",
"calendar_id": "1",
"menu_title": "Atypical Menu",
"dish_name": "Garden Fresh Salad",
"dish_id": "211",
"day": "Fri",
"Schedule": "weekly"
},
{
"school_name": "LittleStar ",
"calendar_id": "1",
"menu_title": "Atypical Menu",
"dish_name": "A Test",
"dish_id": "213",
"day": "Mon",
"Schedule": "weekly"
}, {
"school_name": "LittleStar ",
"calendar_id": "1",
"menu_title": "Atypical Menu",
"dish_name": "Hamburger",
"dish_id": "56",
"day": "Fri",
"Schedule": "weekly"
}, {
"school_name": "LittleStar ",
"calendar_id": "1",
"menu_title": "Atypical Menu",
"dish_name": "Tofu Caesar Salad w\/ Roll",
"dish_id": "149",
"day": "Fri",
"Schedule": "weekly"
}]
}
HelloworldActivity.java
public class HelloworldActivity extends Activity {
int count = 0;
Date date1;
Date date2;
String id;
String title;
String byweekdate;
int IOConnect = 0;
String mVal2;
String mVal3;
String mVal9;
String SelectMenuAPI;
String url;
String URL;
String URL2, URL3, URL4;
String menu_title;
JSONArray school;
ListView listCategory;
String status;
String message;
String _response;
String SelectMenuAPI2;
TextView menu_nametxt;
thirdstepAdapter cla;
static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> school_name = new ArrayList<String>();
static ArrayList<String> menu_name = new ArrayList<String>();
static ArrayList<String> dish_name = new ArrayList<String>();
static ArrayList<String> dish_ID = new ArrayList<String>();
static ArrayList<String> day = new ArrayList<String>();
static ArrayList<Long> Vacation_ID = new ArrayList<Long>();
static ArrayList<String> Vacation_name = new ArrayList<String>();
static ArrayList<String> Vacation_Date = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listCategory = (ListView) findViewById(R.id.thirdscreenlist);
menu_nametxt = (TextView) findViewById(R.id.menu_name);
cla = new thirdstepAdapter(HelloworldActivity.this);
listCategory.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
}
});
new getDataTask().execute();
}
void clearData() {
Category_ID.clear();
school_name.clear();
menu_name.clear();
dish_name.clear();
dish_ID.clear();
day.clear();
Vacation_ID.clear();
Vacation_name.clear();
Vacation_Date.clear();
}
public class getDataTask extends AsyncTask<Void, Void, Void> {
getDataTask() {
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
if ((Category_ID.size() > 0) || IOConnect == 0) {
listCategory.setAdapter(cla);
menu_nametxt.setText(mVal2);
// cla.notifyDataSetChanged();
}
}
}
public void parseJSONData() {
clearData();
SelectMenuAPI = "http://198.57.208.46/~school/index.php/api/index/getMenuBySchool?sid=147&lid=1";
URL = SelectMenuAPI;
URL2 = URL.replace(" ", "%20");
try {
Log.i("url", "" + URL2);
HttpClient client = new DefaultHttpClient();
HttpConnectionParams
.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(URL2);
HttpResponse response = client.execute(request);
HttpEntity resEntity = response.getEntity();
_response = EntityUtils.toString(resEntity);
JSONObject json2 = new JSONObject(_response);
status = json2.getString("status");
if (status.equals("1")) {
JSONArray school = json2.getJSONArray("data");
for (int i = 0; i < school.length(); i++) {
JSONObject object = school.getJSONObject(i);
if (count == 1) {
count = 0;
break;
} else
if (object.getString("Schedule").equals("weekly")) {
if (object.getString("day").equals("Fri")) {
Category_ID.add((long) i);
school_name.add(object.getString("school_name"));
dish_ID.add(object.getString("dish_id"));
dish_name.add(object.getString("dish_name"));
menu_name.add(object.getString("menu_title"));
day.add(object.getString("day"));
count = count + 1;
String[] mVal = new String[school.length()];
for (int k = 0; k < school.length(); k++) {
mVal[k] = school.getJSONObject(k).getString(
"menu_title");
message = "weekly";
mVal2 = mVal[0];
// count = count + 1;
}
} else {
}
} else if (object.getString("Schedule").equals("biweekly")) {
if (object.getString("day").equals(byweekdate)) {
Category_ID.add((long) i);
school_name.add(object.getString("school_name"));
menu_name.add(object.getString("menu_title"));
day.add(object.getString("day"));
String[] mVal = new String[school.length()];
for (int k = 0; k < school.length(); k++) {
mVal[k] = school.getJSONObject(k).getString(
"menu_title");
}
message = "weekly";
mVal2 = mVal[0];
dish_name.add(object.getString("dish_name"));
count = count + 1;
} else {
}
} else {
}
}
} else {
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Try like this hope this help u
try {
JSONObject jb = new JSONObject(myjsonstring);
String totalitems = jb.getString("totalItems");
Log.i("......", "" + totalitems);
String totalpages = jb.getString("totalPages");
String itemsPerPage = jb.getString("itemsPerPage");
String currentPage = jb.getString("currentPage");
JSONArray jarr = jb.getJSONArray("items");
for (int i = 0; i < jarr.length(); i++) {
JSONObject jb1 = jarr.getJSONObject(i);
String id = jb1.getString("id");
String categoy = jb1.getString("category");
String title = jb1.getString("title");
String pic = jb1.getString("thumbnail");
Log.i("........", id);
}
} catch (Exception e) {
}
//HTTP CLASS
public static String sendRequest(String url) {
String result = "";
try {
HttpClient client = new DefaultHttpClient();
HttpParams httpParameters = client.getParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
HttpConnectionParams.setTcpNoDelay(httpParameters, true);
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
InputStream ips = response.getEntity().getContent();
BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"));
StringBuilder sb = new StringBuilder();
String s;
while (true) {
s = buf.readLine();
if (s == null || s.length() == 0)
break;
sb.append(s);
}
buf.close();
ips.close();
result = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}

Categories

Resources