convert "JSON data to textview" to "JSON data to listview" - android

Hello i have a working code that displays a twitter timeline into a textview:
void examineJSONdata()
{
TextView tvData = (TextView) findViewById(R.id.txtData);
try
{
String x = "";
InputStream is = this.getResources().openRawResource(R.raw.jsontwitter);
byte [] buffer = new byte[is.available()];
while (is.read(buffer) != -1);
String jsontext = new String(buffer);
JSONArray entries = new JSONArray(jsontext);
x = "JSON parsed.\nThere are [" + entries.length() + "]\n\n";
int i;
for (i=0;i<entries.length();i++)
{
JSONObject post = entries.getJSONObject(i);
x += "------------\n";
x += "Date:" + post.getString("created_at") + "\n";
x += "Post:" + post.getString("text") + "\n\n";
}
tvData.setText(x);
}
catch (Exception je)
{
tvData.setText("Error w/file: " + je.getMessage());
}
}
Now i want to try a ListView instead of a TextView
I have found a code on StackOverFlow Android App: JSON array from web to listview
ListView list = (ListView) findViewById(...);
String json = "[\"Country1\",\"Country2\",\"Country3\"]";
try {
JSONArray array = (JSONArray) new JSONTokener(json).nextValue();
String[] stringarray = new String[array.length()];
for (int i = 0; i < array.length(); i++) {
stringarray[i] = array.getString(i);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, stringarray);
list.setAdapter(adapter);
} catch (JSONException e) {
// handle JSON parsing exceptions...
}
I have tried to do this but I can't get i work
Would someone help convert the code with me? I think all the neccessary info is in the first code.

String x = "";
InputStream is = this.getResources().openRawResource(R.raw.jsontwitter);
byte [] buffer = new byte[is.available()];
while (is.read(buffer) != -1);
String jsontext = new String(buffer);
JSONArray array = new JSONArray(jsontext);
String[] stringarray = new String[array.length()];
and
int i;
for (i=0;i<array.length();i++)
{
JSONObject post = array.getJSONObject(i);
String temp;
temp += "Date:" + post.getString("created_at") + "\n";
temp += "Post:" + post.getString("text");
stringarray[i]=temp;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, stringarray);
list.setAdapter(adapter);

Related

How to get String Array from JSON Object

I am trying to get a list of available numbers from the following json object
void doJSONParser(String str)
{
try {
JSONObject order = new JSONObject(str);
JSONArray index = order.getJSONArray("webnautes");
for(int i = 0; i < index.length(); i++)
{
JSONObject tt = index.getJSONObject(i);
name += "name: " + tt.getString("name")+"\n";
phone = new String[tt.getString("phone").length()];
//phone += "phone: " + tt.getString("phone")+"\n";
}
Log.d("JSON DATA:", name);
Log.d("JSON DATA:", phone.toString());
}
catch (JSONException e)
{
e.printStackTrace();
Log.d("JSON ERROR", e.getLocalizedMessage());
}
}
Try this
JSONArray phoneJson = tt.getJSONArray("phone");
String[] arr = new String[phoneJson.length()];
for(int i = 0; i < phoneJson.length(); i++)
arr[i] = phoneJson.getString(i);

I am getting error as value of java.lang.String cannot be converted to JSONObject [duplicate]

This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 5 years ago.
my JSONResponse looks as follows
[["1","somevalue","1234567890","1239876093","some"], ["2","somevalue","1234567890","1234567890","some"]]
and code accessing it is as follows
try{
String[] details = {""};
JSONArray array1 = new JSONArray(response);
JSONArray array = array1.getJSONArray(0);
JSONObject object;
//print(array.length() + "");
for(int i = 0; i < array.length(); i++){
object = array.getJSONObject(i);
details[i] = object.getString("roll") + " " + object.getString("name");
ArrayList<String> list = new ArrayList<>();
list.addAll(Arrays.asList(details));
ArrayAdapter<String> defaulters = new ArrayAdapter<String>(ShowDefaulters.this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(defaulters);
}
}
catch (Exception e){
print(e.getMessage());
}
You must get jsonarray on object array. example:
private void test(){
String json_text ="[[\"1\",\"somevalue\",\"1234567890\",\"1239876093\",\"some\"], [\"2\",\"somevalue\",\"1234567890\",\"1234567890\",\"some\"]]";
try{
JSONArray array1 = new JSONArray(json_text);
JSONArray array = array1.getJSONArray(0);
Log.e("ARR", array.toString());
JSONArray user_arr = new JSONArray(array.toString());
for(int i=0; i< user_arr.length(); i++){
Log.e("USER", user_arr.get(i).toString());
}
}
catch (Exception e){
Log.e("ERROR", e.getMessage());
}
}
or:
private void test(){
String json_text ="[[\"1\",\"somevalue\",\"1234567890\",\"1239876093\",\"some\"], [\"2\",\"somevalue\",\"1234567890\",\"1234567890\",\"some\"]]";
try{
JSONArray array1 = new JSONArray(json_text);
JSONArray array = array1.getJSONArray(0);
Log.e("ARR", array.toString());
JSONArray user_arr = new JSONArray(array.toString());
Log.e("USER", "roll: " + user_arr.get(0).toString());
Log.e("USER", "name: " + user_arr.get(1).toString());
}
catch (Exception e){
Log.e("ERROR", e.getMessage());
}
}

Got String Data from Internal Storage When i set it to listview only last item is displayed

Got String Data from Internal Storage.When i tried to display that data on listview only last item is displayed.
Here is my code.
listView=(ListView)findViewById(R.id.listview);
Scanner s = null;
try {
s = new Scanner(new BufferedReader(new FileReader("/storage/sdcard0/client_new.txt")));
while (s.hasNext()) {
String str = s.next();
char[] myChar = str.toCharArray();
System.out.println(myChar);
String str_new = String.valueOf(myChar);
String[] items={str_new};
final ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < items.length; ++i)
{
list.add(items[i]);
}
Toast.makeText(ExistingContacts.this,str_new,Toast.LENGTH_LONG).show();
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_dropdown_item,list);
listView.setAdapter(adapter);
}
}catch (Exception e)
{
e.printStackTrace();;
}
use final ArrayList list = new ArrayList(); before while loop
listView=(ListView)findViewById(R.id.listview);
Scanner s = null;
try {
s = new Scanner(new BufferedReader(new FileReader("/storage/sdcard0/client_new.txt")));
final ArrayList<String> list = new ArrayList<String>();
while (s.hasNext()) {
String str = s.next();
char[] myChar = str.toCharArray();
System.out.println(myChar);
String str_new = String.valueOf(myChar);
String[] items={str_new};
for (int i = 0; i < items.length; ++i)
{
list.add(items[i]);
}
Toast.makeText(ExistingContacts.this,str_new,Toast.LENGTH_LONG).show();
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_dropdown_item,list);
listView.setAdapter(adapter);
}
}catch (Exception e)
{
e.printStackTrace();;
}

can't fill array NewsData[] NewsData_data

write Custom ArrayAdapter by example: http://www.ezzylearning.com/tutorial.aspx?tid=1763429&q=customizing-android-listview-items-with-custom-arrayadapter
i can't fill array in cycle.
working example:
Weather weather_data[] = new Weather[]
{ new Weather("http://www.ezzylearning.com/images/ImagesNew/net_framework.png", "Cloudy"),
new Weather("http://www.ezzylearning.com/images/ImagesNew/net_framework.png", "Showers")
};
my code:
NewsData[] NewsData_data;
// build hash set for list view
public void ListDrwaer() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("news");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String header = jsonChildNode.optString("header");
String short_text = jsonChildNode.optString("short_text");
String team = jsonChildNode.optString("team");
String datatime = jsonChildNode.optString("datatime");
String photo_url = jsonChildNode.optString("photo_url");
NewsData_data[i] = new NewsData(header, short_text, team, datatime, photo_url);
}
} catch (JSONException e) {
Toast.makeText(getActivity(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
NewsDataAdapter adapter = new NewsDataAdapter(getActivity(),
R.layout.news_details, NewsData_data);
listView.setAdapter(adapter);
}
You need to initialize this array:
NewsData[] NewsData_data;
// build hash set for list view
public void ListDrwaer() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("news");
NewsData_data=new NewsData[jsonMainNode.length()];//<------------HERE
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String header = jsonChildNode.optString("header");
String short_text = jsonChildNode.optString("short_text");
String team = jsonChildNode.optString("team");
String datatime = jsonChildNode.optString("datatime");
String photo_url = jsonChildNode.optString("photo_url");
NewsData_data[i] = new NewsData(header, short_text, team, datatime, photo_url);
}
} catch (JSONException e) {
Toast.makeText(getActivity(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
NewsDataAdapter adapter = new NewsDataAdapter(getActivity(),
R.layout.news_details, NewsData_data);
listView.setAdapter(adapter);
}
Simplified answer: your array is not initialized. Longer answer, you have to know how big it is going to be, then initialize it to that size. A simple example:
NewsData[] NewsData_data;
ArrayList<NewsData> newsDataArray = new ArrayList<NewsData>();
String header = "header";
String short_text = "short_text";
String team = "team";
String datatime = "datatime";
String photo_url = "photo_url";
newsDataArray.add(new NewsData(header, short_text, team, datatime, photo_url));
newsDataArray.add(new NewsData(header, short_text, team, datatime, photo_url));
NewsData_data = new NewsData[newsDataArray.size()];
newsDataArray.toArray(NewsData_data);
System.out.println(NewsData_data);

Android update sqlite table

I have written Update table using dbAdapter.
public void loadDownloadData() {
SoapPrimitive responsePrimitiveData;
//Loop Table list
for (int i = 0; i < tablesName.size(); i++) {
try {
responsePrimitiveData = soapPrimitiveData(tablesName.get(i));
if (responsePrimitiveData != null) {
try {
String result = responsePrimitiveData.toString();
JSONObject jsonobject = new JSONObject(result);
JSONArray array = jsonobject.getJSONArray("Table1");
int max = array.length();
// Loop each table data
for (int j = 0; j < max; j++) {
JSONObject obj = array.getJSONObject(j);
JSONArray names = obj.names();
StringBuilder strFields = new StringBuilder();
StringBuilder strValues = new StringBuilder();
String[] strToFields = new String[names.length()];
String[] strToFieldsVal = new String[names.length()];
//getting the Json name, values in separate string array
for (int k = 0; k < names.length(); k++) {
String name = names.getString(k);
strToFields[k] = names.getString(k);
String strVal;
if(obj.getString(name)== null){
strVal="";
strToFieldsVal[k]="";
}else{
if(obj.getString(name).equals(" ")){
strVal="";
strToFieldsVal[k]="";
}else{
String tmp1 = obj.getString(name).replaceAll("\\s+", " ");
String tmp = tmp1.replaceAll("\\s+", " ");
strVal =tmp.replaceAll("\\s+", " ");
strToFieldsVal[k]=strVal;
}
}
strFields.append(name + ",");
strValues.append(strVal+",");
} //end of json for loop
strFields.deleteCharAt(strFields.length() - 1);
strValues.deleteCharAt(strValues.length() - 1);
if(getTableUpdateType(tablesName.get(i)).equals("1")){
String actualtable = getAndroidTablename(tablesName.get(i));
if(isTableRecords(tablesName.get(i))){
String[] strWhereField = getTablePrimaryKey(tablesName.get(i),strBusinessUnit);
String[] strWhereFieldVal = new String[strWhereField.length];
StringBuilder whereFields = new StringBuilder();
for (int a = 0; a < strWhereField.length; a++) {
strWhereFieldVal[a] = obj.getString(strWhereField[a]);
whereFields.append(strWhereField[a] + "= ? and ");
}
whereFields.delete(whereFields.length() - 4, whereFields.length());
updateTableRecords(actualtable, strToFields, strToFieldsVal,whereFields.toString() ,strWhereFieldVal);
}else{
insertTableRecords(actualtable, strToFields, strToFieldsVal);
}
}else if(getTableUpdateType(tablesName.get(i)).equals("2")){
}else if(getTableUpdateType(tablesName.get(i)).equals("3")){
}else{
}
}//end of each table data
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
}
and I called like update method:
public void updateTableRecords(String strTableName, String[] strToFields, String[] strValues,String strWhereField ,String[] strWhereFieldVal){
DBAdapter dbAdapter = DBAdapter.getDBAdapterInstance(DownlaodTableActivity.this);
dbAdapter.openDataBase();
ContentValues initialValues = new ContentValues();
for(int i=0 ;i<strToFields.length;i++){
initialValues.put(strToFields[i],strValues[i]);
}
long n = dbAdapter.updateRecordsInDB(strTableName, initialValues, strWhereField, strWhereFieldVal);
System.out.println( " -- n--- " + n);
Toast.makeText(DownlaodTableActivity.this, n+" rows updated", Toast.LENGTH_SHORT).show();
}
I want to generate update statement dynamic way. From These code I put Where part also.But I did not generate where clause.
see :
UPDATE strTableName SET ExecutiveCode=?, FreeIssuePrefix=?, DisPaySchedulePrefix=?, NextFreeIssueNo=?, NextReturnNo=?, UploadedType=?, DisNextFOCNo=?, DisNextFreeIssueNo=?
Please help me How to give the Where clase(Here I gave String & arguments as string array)
Thanks in advance...
try like this
dbAdapter.updateRecordsInDB(strTableName, initialValues,""+whereField+"='"+whereFieldValue+"'",null);
if your whereField field's type is number then don't use ''
If you have to compare with multiple values use
String where="";
for(int i=0;i<strWhereField.length();i++)
{
where=where+whereField[i]+"='"+strWhereFieldValue[i]+"'"
if(i<(strWhereField.length()-1)) where=where+" and"
}
dbAdapter.updateRecordsInDB(strTableName, initialValues,where,null);

Categories

Resources