trouble with adding Spinner in CSipSimple - android

I'm trying to add spinner in my CSipSimple account registration form. but i'm having error at few lines.
first i'm having error at
accountUserName = (Spinner) findViewById("username");
findViewById is undefined.
Second is at
ArrayAdapter dataAdapter = new ArrayAdapter(this, R.layout.spinner_item, list);
saying Constructor ArrayAdapter is undefined.
this code was working fine in a saperate program but when i tried to put this code in CSipsimple Basic.java file it showed these two errors. can someone please help me?
public class Basic extends BaseImplementation {
protected static final String THIS_FILE = "Basic W";
InputStream is=null;
String result=null;
String line=null;
JSONObject json = null;
private Spinner accountUserName;
private EditTextPreference accountDisplayName;
//private EditTextPreference accountUserName;
private EditTextPreference accountServer;
private EditTextPreference accountPassword;
private void bindFields() {
accountDisplayName = (EditTextPreference) findPreference("display_name");
accountUserName = (Spinner) findViewById("username");
accountServer = (EditTextPreference) findPreference("server");
accountPassword = (EditTextPreference) findPreference("password");
}
public void fillLayout(final SipProfile account) {
bindFields();
accountDisplayName.setText(account.display_name);
//fetching values fro mysql database
String serverFull = account.reg_uri;
if (serverFull == null) {
serverFull = "";
}else {
serverFull = serverFull.replaceFirst("sip:", "");
}
ParsedSipContactInfos parsedInfo = SipUri.parseSipContact(account.acc_id);
//accountUserName.setText(parsedInfo.userName);
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.xx.xxx/conIds.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(),e.toString(),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();
System.out.println(result);
Log.e("Pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
//
try
{
JSONArray NJA=new JSONArray(result);
String arr=NJA.getString(1);
Log.d("My arry", ""+arr);
JSONArray JA=new JSONArray(arr);
final String[] str2 = new String[JA.length()];
for(int i=0;i<JA.length();i++)
{
str2[i] = JA.getString(i);
}
List<String> list = new ArrayList<String>();
for(int i=0;i<str2.length;i++)
{
list.add(str2[i]);
}
Collections.sort(list);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, R.layout.spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
accountUserName.setAdapter(dataAdapter);
accountUserName.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long id)
{
// TODO Auto-generated method stub
String Item=accountUserName.getSelectedItem().toString();
Toast.makeText(getApplicationContext(), Item,Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
});
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
accountServer.setText(serverFull);
accountPassword.setText(account.data);
}

Have you imported android.app.Activity (in which findViewById(int) is defined) and android.widget.ArrayAdapter?

Related

Android ListView duplicates data after pressing back button

I have a listview populated by the data from mysql database. It works fine but when I select an item then press back , the previous listview fecth again data from database that duplicates the items in my listview.
Here's is my code :
public class CityPage extends Activity{
Activity context;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
ProgressDialog pd;
CityAdapter cityAdapter;
ListView listCity;
ArrayList<City> records;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_city_page);
context = this;
records = new ArrayList<City>();
listCity = (ListView) findViewById(R.id.cities);
cityAdapter = new CityAdapter(context, R.layout.city_layout, R.id.city_name, records);
listCity.setAdapter(cityAdapter);
listCity.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent myIntent = new Intent(view.getContext(),City_attractions.class);
Toast.makeText(CityPage.this, "Opening", Toast.LENGTH_LONG).show();
String info1 = records.get(position).getCityName();
String info2 = records.get(position).getDescription();
myIntent.putExtra("info1", info1);
myIntent.putExtra("info2", info2);
startActivity(myIntent);
}
});
}
#Override
protected void onStart() {
super.onStart();
fetchCity fetch = new fetchCity();
fetch.execute();
}
private class fetchCity extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
}
protected Void doInBackground(Void... params) {
InputStream is = null;
String result = "";
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://iguideph-001-site1.btempurl.com/getcity.php");
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
} catch (Exception e) {
if (pd != null)
pd.dismiss(); //close the dialog if error occurs
Log.e("ERROR", e.getMessage());
}
//convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("ERROR", "Error converting result " + e.toString());
}
//parse json data
try {
// Remove unexpected characters that might be added to beginning of the string
result = result.substring(result.indexOf(""));
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
City p = new City();
p.setCityName(json_data.getString("place_name"));
p.setDescription(json_data.getString("description"));
records.add(p);
}
} catch (Exception e) {
Log.e("ERROR", "Error pasting data " + e.toString());
}
return null;
}
protected void onPostExecute(Void result) {
if (pd != null) pd.dismiss(); //close dialog
Log.e("size", records.size() + "");
cityAdapter.notifyDataSetChanged(); //notify the ListView to get new records
}
}
}
try remove those lines from onstart() and put them inside oncreate() function
fetchCity fetch = new fetchCity();
fetch.execute();
Good luck !

how to print value from out of main method toinside main method [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
how to access value which is out of main class? i want to print value of elementarytxtview
in main class in parameter but is print null value of in parameter i want to pass elementarytextview value in parameter to other activity
public class HomeMenu extends Activity {
ImageButton imgNews, imgContact, imgSetting;
ListView listMainMenu;
ListView Middleschoollist, HighSchoollist, Atipicalschoollist;
String status;
firstscreenadapter mma;
String SelectMenuAPI;
String SelectMenuAPI2;
String url1;
String elementry;
// String High;
String message;
TextView Elementarytxt, Middletxt, Hightxt, Atypicaltxt;
static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> Category_name = new ArrayList<String>();
String elementarytxtview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.firstscreenfinal);
ExpandableHeightListView listMainMenu = (ExpandableHeightListView)
findViewById(R.id.listMainMenu11);
ExpandableHeightListView Middleschoollist = (ExpandableHeightListView)
findViewById(R.id.listMainMenu22);
ExpandableHeightListView HighSchoollist = (ExpandableHeightListView)
findViewById(R.id.listMainMenu33);
ExpandableHeightListView Atipicalschoollist = (ExpandableHeightListView)
findViewById(R.id.listMainMenu44);
Elementarytxt = (TextView) findViewById(R.id.Elementaryschool);
Middletxt = (TextView) findViewById(R.id.MiddleSchool);
Hightxt = (TextView) findViewById(R.id.HighSchool);
Atypicaltxt = (TextView) findViewById(R.id.AtipicalSchool);
mma = new firstscreenadapter(this);
if (!Utils.isNetworkAvailable(HomeMenu.this)) {
Toast.makeText(HomeMenu.this, "NO NETWORK Available",
Toast.LENGTH_SHORT).show();
}
if (!Utils.isUserOnline(this)) {
Toast.makeText(this, "No NETWORK", Toast.LENGTH_LONG).show();
}
url1 = "http://198.57.208.46/~school/ajax.php?action=get_school";
listMainMenu.setAdapter(mma);
Middleschoollist.setAdapter(mma);
HighSchoollist.setAdapter(mma);
Atipicalschoollist.setAdapter(mma);
listMainMenu.setExpanded(true);
Middleschoollist.setExpanded(true);
HighSchoollist.setExpanded(true);
Atipicalschoollist.setExpanded(true);
Toast.makeText(this, elementarytxtview, Toast.LENGTH_SHORT).show();
listMainMenu.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Intent iMenuList = new Intent(HomeMenu.this,
SecondStep.class);
iMenuList.putExtra("category_name",xxx.xxx.xxxx/~school/index.php
/api/index/getschools?mg="+ Category_name.get(position)+ "&sl="+elementarytxtview);
startActivity(iMenuList);
}
});
parseJSONData();
}
void clearData() {
Category_ID.clear();
Category_name.clear();
}
public void parseJSONData() {
SelectMenuAPI = Utils.Homemenu2;
SelectMenuAPI2 = Utils.Homemenu;
clearData();
try {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams
.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(SelectMenuAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(
atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null) {
str += line;
}
HttpClient client2 = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client2.getParams(),
15000);
HttpConnectionParams.setSoTimeout(client2.getParams(), 15000);
HttpUriRequest request2 = new HttpGet(SelectMenuAPI2);
HttpResponse response2 = client2.execute(request2);
InputStream atomInputStream2 = response2.getEntity().getContent();
BufferedReader in2 = new BufferedReader(new InputStreamReader(
atomInputStream2));
String line2;
String str2 = "";
while ((line2 = in2.readLine()) != null) {
str2 += line2;
}
JSONObject json3 = new JSONObject(str2);
// message = json2.getString("message");
status = json3.getString("status");
if (status.equals("1")) {
JSONArray school2 = json3.getJSONArray("data");
String[] mVal = new String[school2.length()];
for (int i = 0; i < school2.length(); i++) {
mVal[i] =
school2.getJSONObject(i).getString("title");
Elementarytxt.setText(mVal[0]);
Middletxt.setText(mVal[1]);
Hightxt.setText(mVal[2]);
Atypicaltxt.setText(mVal[3]);
}
elementarytxtview = mVal[0];
}
JSONObject json2 = new JSONObject(str);
// message = json2.getString("message");
status = json2.getString("status");
if (status.equals("1")) {
// JSONObject data = json.getJSONObject("data");
JSONArray school = json2.getJSONArray("data");
for (int i = 0; i < school.length(); i++) {
JSONObject object = school.getJSONObject(i);
//
Category_ID.add(Long.parseLong(object.getString("id")));
Category_ID.add((long) i);
Category_name.add(object.getString("title"));
}
} else {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
} 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();
}
}
}
elementarytxtview is not initialized before you try to show it via Toast. At first you need to put some value in it.
I'm not a 100% sure of what you mean.
But if you want to access variables easily between classes, you should make the String elementarytxtview; public static
Thereby: public static String elementarytxtview;
What that means is basically that the variable is shared and can be used between all classes. Just by writing HomeMenu.elementarytxtview; in your case.
You are showing the Toast in the onCreate method which runs before your parseJSONData() method. You haven't initialized String elementarytxtview therefore it will show null because you only declared the variable.

Spinners are empty

I am trying to populate spinners with data from MySQL (I am having to rows) but they stay empty. Also, those spinners should be dependent on each other. Any ideas why? When I call url in local host it returns right values, so the PHP is working fine(example of one row from PHP: [{"Grad":"Beograd","Predmet":"matematika"}...], I m more worried about putting those rows in a list.
public class IzboraGrada extends Activity {
Spinner spinner1, spinner2;
private Button button,izlaz;
static String str_grad,str_predmet,url;
InputStream is=null;
String result=null;
String line=null;
String[] grad, predmet;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_izbora_grada);
spinner1=(Spinner) findViewById(R.id.spinner1);
spinner2=(Spinner) findViewById(R.id.spinner2);
final List<String> list1=new ArrayList<String>();
final List<String> list2=new ArrayList<String>();
Button b=(Button) findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.14/test/spinner1.php");
HttpResponse response = httpclient.execute(httppost);
Log.e("Fail 1", "3");
HttpEntity entity = response.getEntity();
Log.e("Fail 1", "4");
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();
finish();
}
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();
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
try
{
JSONArray JA=new JSONArray(result);
JSONObject json= null;
grad = new String[JA.length()];
predmet = new String[JA.length()];
for(int i=0;i<JA.length();i++)
{
json=JA.getJSONObject(i);
grad[i] = json.getString("Grad");
predmet[i]=json.getString("Predmet");
}
Toast.makeText(getApplicationContext(), "sss",Toast.LENGTH_LONG).show();
for(int i=0;i<grad.length;i++)
{
list1.add(grad[i]);
list2.add(predmet[i]);
}
spinner_fn();
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
//login.this.finish();
}
}
});
}
private void spinner_fn() {
// TODO Auto-generated method stub
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_spinner_item, grad);
dataAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter1);
ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_spinner_item, predmet);
dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataAdapter2);
spinner1.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long id)
{
// TODO Auto-generated method stub
spinner2.setSelection(position);
}
#Override
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
});
spinner2.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long arg3) {
// TODO Auto-generated method stub
spinner1.setSelection(position);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
And PHP code:
$con = mysqli_connect($host, $user, $pwd, $db);
if(mysqli_connect_errno($con)) {
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
$sql = "SELECT Grad, Predmet FROM lista";
$result = mysqli_query($con, $sql);
$rows = array();
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$rows[] = $row;
}
mysqli_close($con);
echo json_encode($rows);
you aren't populating your spinners, look to a part of your code ;
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(getApplicationContext(),
dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Android is reading it as one line, without valid references to the right data. Please replace it by the following,
// adapter for spinner
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(getApplicationContext(), $$$, list1);
// set layout
dataAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
replace the $$$ to the spinner item-id in your XML layout. Do the same for spinner2

Can get information from JSON API

im trying to get some information from a site BayFiles.net using their API.
The call URL is: http://api.bayfiles.net/v1/account/files?session=SESSION-ID
The error i get is:
07-04 13:54:39.525: E/log_tag(588): Error parsing data org.json.JSONException: Value at error of type java.lang.String cannot be converted to JSONArray
The JSON output when correct sessionID is something like this:
{
"error": "",
"S8tf": {
"infoToken": "wCfhXe",
"deleteToken": "gzHTfGcF",
"size": 122484,
"sha1": "8c4e2bbc0794d2bd4f901a36627e555c068a94e6",
"filename": "Screen_Shot_2013-07-02_at_3.52.23_PM.png"
},
"S29N": {
"infoToken": "joRm6p",
"deleteToken": "IL5STLhq",
"size": 129332,
"sha1": "b4a03897121d0320b82059c36f7a10a8ef4c113d",
"filename": "Stockholmsyndromet.docx"
}
}
however i cant get to catch the respons and show it in a listview.
This is my activity:
public class FilesActivity extends SherlockListActivity implements
OnClickListener {
private ProgressDialog mDialog;
ActionBar ABS;
TextView session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dblist);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Files");
JsonAsync asyncTask = new JsonAsync();
// Using an anonymous interface to listen for objects when task
// completes.
asyncTask.setJsonListener(new JsonListener() {
#Override
public void onObjectReturn(JSONObject object) {
handleJsonObject(object);
}
});
// Show progress loader while accessing network, and start async task.
mDialog = ProgressDialog.show(this, getSupportActionBar().getTitle(),
getString(R.string.loading), true);
asyncTask.execute("http://api.bayfiles.net/v1/account/files?session=" + PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getString("sessionID", "defaultStringIfNothingFound"));
//session = (TextView)findViewById(R.id.textView1);
//session.setText(PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getString("sessionID", "defaultStringIfNothingFound"));
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
private void handleJsonObject(JSONObject object) {
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
try {
JSONArray shows = object.getJSONArray("error");
for (int i = 0; i < shows.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = shows.getJSONObject(i);
//map.put("video_location", "" + e.getString("video_location"));
mylist.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist, R.layout.dbitems,
new String[] { "video_title", "video_location" }, new int[] { R.id.item_title,
R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv
.getItemAtPosition(position);
//Intent myIntent = new Intent(ListShowsController.this,
// TestVideoController.class);
//myIntent.putExtra("video_title", o.get("video_title"));
//myIntent.putExtra("video_channel", o.get("video_channel"));
//myIntent.putExtra("video_location", o.get("video_location"));
//startActivity(myIntent);
}
});
if (mDialog != null && mDialog.isShowing()) {
mDialog.dismiss();
}
}
}
and my JSONfunctions:
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url){
InputStream is = null;
String result = "";
JSONObject jArray = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
// Add your data
/*List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("key", "stianxxs"));
nameValuePairs.add(new BasicNameValuePair("secret", "mhfgpammv9f94ddayh8GSweji"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); */
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
//HttpResponse response = httpclient.execute(httppost);
HttpEntity httpEntity = response.getEntity();
is = httpEntity.getContent();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
try{
jArray = new JSONObject(result);
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return jArray;
}
}
Any help is much appreciated!
As 'error' is not JSONArray it is giving you parsing error.
JSONArray shows = object.getJSONArray("error");
Change you line to
String shows = object.getString("error");
You can refer to these link for JSON Parsing.
https://stackoverflow.com/a/16938507/1441666

Show data in listview with Asynctask

I success show my data from web service JSON in listview, but I want to add Asyntask.
Where I can put code Asyntask in my code.
This my code to show data in list view
public class Jadwal_remix extends ListActivity {
String v_date;
JSONArray r_js = null;
ArrayList<HashMap<String, String>> myArray = new ArrayList<HashMap<String,String>>();
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
String status ="";
String date = "";
String result = "";
String url = "http://10.0.2.2/remix/view_list.php";
JSONParser jParser = new JSONParser();
JSONObject json = jParser.AmbilJson(url);
try
{
r_js = json.getJSONArray("view_list");
for (int i =0; i < r_js.length(); i++)
{
String my_array = "";
JSONObject ar = r_js.getJSONObject(i);
status = ar.getString("st");
date = ar.getString("date");
result = ar.getString("result");
if (status.trim().equals("er"))
{
my_array += "Sorry "+result;
HashMap<String, String> map = new HashMap<String, String>();
map.put("result", my_array);
myArray.add(map);
}
else
{
my_array += "Date : "+date+" "+"Result : "+result;
HashMap<String, String> map = new HashMap<String, String>();
map.put("result", my_array);
myArray.add(map);
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
adapter_listview();
}
public void adapter_listview() {
ListAdapter adapter = new SimpleAdapter(this, jadwalRemix,R.layout.my_list,new String[] { "result"}, new int[] {R.id.txtResult});
setListAdapter(adapter);
}
}
And this JSONParser
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject AmbilJson(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Where can I put code for Asyntask?
Ok, I get sample code, and my code now like this
public class Jadwal_remix extends ListActivity {
String v_date;
JSONArray r_js = null;
ArrayList<HashMap<String, String>> myArray = new ArrayList<HashMap<String,String>>();
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
private class myProses extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog;
protected void onPreExecute() {
dialog = ProgressDialog.show(Jadwal_remix.this, "", "Loading... Please wait", true);
}
protected Void doInBackground(Void... params) {
String status ="";
String date = "";
String result = "";
String url = "http://10.0.2.2/remix/view_list.php";
JSONParser jParser = new JSONParser();
JSONObject json = jParser.AmbilJson(url);
try
{
r_js = json.getJSONArray("view_list");
for (int i =0; i < r_js.length(); i++)
{
String my_array = "";
JSONObject ar = r_js.getJSONObject(i);
status = ar.getString("st");
date = ar.getString("date");
result = ar.getString("result");
if (status.trim().equals("er"))
{
my_array += "Sorry "+result;
HashMap<String, String> map = new HashMap<String, String>();
map.put("result", my_array);
myArray.add(map);
}
else
{
my_array += "Date : "+date+" "+"Result : "+result;
HashMap<String, String> map = new HashMap<String, String>();
map.put("result", my_array);
myArray.add(map);
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
return null;
protected void onPostExecute(Void unused) {
adapter_listview();
dialog.dismiss();
}
}
public void adapter_listview() {
ListAdapter adapter = new SimpleAdapter(this, jadwalRemix,R.layout.my_list,new String[] { "result"}, new int[] {R.id.txtResult});
setListAdapter(adapter);
}
}
I'm get problem when server is die, it still loading.
How I can show message ex: can't connect to server?
Working ASyncTask tutorial,
Full ASyncTask Eclipse Project,
and here's some code that I think, when mixed with the above sample, will get you the result with the list that you desire (you'll have to adapt it to your needs a bit, though (pay attention to the list stuff, even though this is from a custom Dialog:
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Kies Facebook-account");
builder.setNegativeButton("Cancel", this);
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogLayout = inflater.inflate(R.layout.dialog, null);
builder.setView(dialogLayout);
final String[] items = {"Red", "Green", "Blue" };
builder.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.v("touched: ", items[which].toString());
}}
);
return builder.create();
}
This is my code please try this one,
MAinActivity.java
public class MyActivity extends Activity {
private ListView contests_listView;
private ProgressBar pgb;
ActivitiesBean bean;
ArrayList<Object> listActivities;
ActivityAdapter adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview);
contests_listView = (ListView) findViewById(R.id.activity_listView);
pgb = (ProgressBar) findViewById(R.id.contests_progressBar);
listActivities = new ArrayList<Object>();
new FetchActivitesTask().execute();
}
public class FetchActivitesTask extends AsyncTask<Void, Void, Void> {
int i =0;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pgb.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
String url = "Your URL Here";
String strResponse = util.makeWebCall(url);
try {
JSONObject objResponse = new JSONObject(strResponse);
JSONArray jsonnodes = objResponse.getJSONArray(nodes);
for (i = 0; i < jsonnodes.length(); i++)
{
String str = Integer.toString(i);
Log.i("Value of i",str);
JSONObject jsonnode = jsonnodes.getJSONObject(i);
JSONObject jsonnodevalue = jsonnode.getJSONObject(node);
bean = new ActivitiesBean();
bean.title = jsonnodevalue.getString(title);
bean.image = jsonnodevalue.getString(field_activity_image_fid);
listActivities.add(bean);
}
}
catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
public void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pgb.setVisibility(View.GONE);
displayAdapter();
}
}
public void displayAdapter()
{
adapter = new ActivityAdapter(this, listActivities);
contests_listView.setAdapter(adapter);
contests_listView.setOnItemClickListener(new OnItemClickListener() {
//#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long id) {
// your onclick Activity
}
});
}
}
util.class
public static String makeWebCall(String url) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet(url);
// HttpPost post = new HttpPost(url);
try {
HttpResponse httpResponse = client.execute(httpRequest);
final int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = httpResponse.getEntity();
InputStream instream = null;
if (entity != null) {
instream = entity.getContent();
}
return iStream_to_String(instream);
}
catch (IOException e) {
httpRequest.abort();
// Log.w(getClass().getSimpleName(), "Error for URL =>" + url, e);
}
return null;
}
public static String iStream_to_String(InputStream is1) {
BufferedReader rd = new BufferedReader(new InputStreamReader(is1), 4096);
String line;
StringBuilder sb = new StringBuilder();
try {
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String contentOfMyInputStream = sb.toString();
return contentOfMyInputStream;
}
}
ActivityBean.java
public class ActivitiesBean implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
public String title;
public String image;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}

Categories

Resources