how to fix getDataTask method error? - android

below is my code there is a problem some where in getDataTask if i remove this class is work fine and print Toast message Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); but what is problem in my getDataTask im parsing below json file problem is some where in doinbackground method help me please
{"status":0,"message":"No such school found"}
public class thirdstep extends Activity {
ListView listCategory;
String status;
String message;
String MenuSelect;
ProgressBar prgLoading;
long Cat_ID;
String Cat_name;
String CategoryAPI;
int IOConnect = 0;
TextView txtAlert;
thirdstepAdapter cla;
static ArrayList<String> Category_ID = new ArrayList<String>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_list2);
ImageButton btnback = (ImageButton) findViewById(R.id.btnback);
listCategory = (ListView) findViewById(R.id.listCategory2);
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
txtAlert = (TextView) findViewById(R.id.txtAlert);
cla = new thirdstepAdapter(thirdstep.this);
new getDataTask().execute();
listCategory.setAdapter(cla);
btnback.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
});
Intent iGet = getIntent();
Cat_ID = iGet.getLongExtra("category_id", 0);
Cat_name = iGet.getStringExtra("category_name");
Toast.makeText(this, Cat_ID + Cat_name, Toast.LENGTH_SHORT).show();
MenuSelect = Utils.MenuSelect;
listCategory.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Intent iMenuList = new Intent(thirdstep.this, fourthscreen.class);
iMenuList.putExtra("Cat_ID",Cat_ID);
iMenuList.putExtra("Menuitem", Category_ID.get(position));
startActivity(iMenuList);
}
});
}
void clearData() {
Category_ID.clear();
Category_name.clear();
Category_image.clear();
}
public class getDataTask extends AsyncTask<Void, Void, Void>{
getDataTask(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(0);
txtAlert.setVisibility(8);
}
}
#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
prgLoading.setVisibility(8);
if((Category_ID.size() > 0) || IOConnect == 0){
listCategory.setVisibility(0);
listCategory.setAdapter(cla);
}else{
txtAlert.setVisibility(0);
}
}
}
public void parseJSONData() {
CategoryAPI = Utils.MenuList + Cat_ID;
clearData();
try {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams
.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(CategoryAPI);
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;
}
JSONObject json = new JSONObject(str);
JSONObject json2 = new JSONObject(str);
status = json2.getString("status");
message = json2.getString("message");
if (status.equals("1")) {
JSONObject data = json.getJSONObject("data");
JSONArray school = data.getJSONArray("menu_groups");
for (int i = 0; i < school.length(); i++) {
JSONObject object = school.getJSONObject(i);
Category_ID.add(object.getString("id"));
Category_name.add(object.getString("title"));
Category_image.add(object.getString("image"));
}
}
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();
}
}
}

You are calling parseJSONData() in doInbackground and you have this
Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); // in parseJSONData()
you cannot update ui from doInbackground. You need to update ui on the ui thread. Return result in doInbackground. In onPostExecute update ui.

Related

parse JSON from URL on Android and display in listview

I'm trying to parse a JSON result from a URL in my Android app.
I have tried a few examples on the Internet, but can't get it to work.
What's the simplest way to fetch the URL and parse the JSON data show it in the listview
Json data :
[{"MemberID":"1","Username":"weerachai","Password":"12345","Name":"Weerachai
Nukitram","Tel":"0819876107","Email":"weerachai#gmail.com"},{"MemberID":"2","Username":"adisorn","Password":"ac143","Name":"Adisorn
Bunsong","Tel":"021978032","Email":"adisorn#gmail.com"},{"MemberID":"3","Username":"surachai","Password":"gg111","Name":"Surachai
Sirisart","Tel":"0876543210","Email":"surachai#gmail.com"}]
Android code :
public class MainActivity extends AppCompatActivity {
ArrayList<HashMap<String, String>> MyArrList;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Permission StrictMode
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
ShowData();
// btnSearch
final Button btnSearch = (Button) findViewById(R.id.btnSearch);
//btnSearch.setBackgroundColor(Color.TRANSPARENT);
// Perform action on click
btnSearch.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ShowData();
}
});
}
public void ShowData()
{
// listView1
final ListView lisView1 = (ListView)findViewById(R.id.listView1);
// keySearch
EditText strKeySearch = (EditText)findViewById(R.id.txtKeySearch);
// Disbled Keyboard auto focus
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);imm.hideSoftInputFromWindow(strKeySearch.getWindowToken(), 0);
String url = "http:...............php";
// Paste Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("txtKeyword", strKeySearch.getText().toString()));
try {
JSONArray data = new JSONArray(getJSONUrl(url,params));
MyArrList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("MemberID", c.getString("MemberID"));
map.put("Username", c.getString("Username"));
map.put("Password", c.getString("Password"));
map.put("Name", c.getString("Name"));
map.put("Email", c.getString("Email"));
map.put("Tel", c.getString("Tel"));
MyArrList.add(map);
}
lisView1.setAdapter(new ImageAdapter(this));
// OnClick Item
lisView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView, int position, long mylng) {
String sMemberID = MyArrList.get(position).get("MemberID").toString();
String sName = MyArrList.get(position).get("Name").toString();
String sTel = MyArrList.get(position).get("Tel").toString();
Intent newActivity = new Intent(MainActivity.this,DetailActivity.class);
newActivity.putExtra("MemberID", sMemberID);
startActivity(newActivity);
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public class ImageAdapter extends BaseAdapter
{
private Context context;
public ImageAdapter(Context c)
{
// TODO Auto-generated method stub
context = c;
}
public int getCount() {
// TODO Auto-generated method stub
return MyArrList.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.activity_column, null);
}
// ColMemberID
TextView txtMemberID = (TextView) convertView.findViewById(R.id.ColMemberID);
txtMemberID.setPadding(10, 0, 0, 0);
txtMemberID.setText(MyArrList.get(position).get("MemberID") +".");
// R.id.ColName
TextView txtName = (TextView) convertView.findViewById(R.id.ColName);
txtName.setPadding(5, 0, 0, 0);
txtName.setText(MyArrList.get(position).get("Name"));
// R.id.ColTel
TextView txtTel = (TextView) convertView.findViewById(R.id.ColTel);
txtTel.setPadding(5, 0, 0, 0);
txtTel.setText(MyArrList.get(position).get("Tel"));
return convertView;
}
}
public String getJSONUrl(String url,List<NameValuePair> params) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Download OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download result..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
}

How to make elements(dynamic) obtained as JSON response, clickable in Android and connecting them to some web link?

The following is the CODE I am using to get the data from Codeforces.com API as JSON response. If anyone can please help me improve this to convert them to clickable links and then attach a web link to them. :
public class Http extends Activity {
TextView httpStuff;
HttpClient client;
JSONObject json;
final static String URL = "http://codeforces.com/api/user.status?handle=";
String m = "";
public static String[] sarr = new String[200];
public static String[] name = new String[200];
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.httpex);
httpStuff = (TextView)findViewById(R.id.tvHttp);
client = new DefaultHttpClient();
new Read().execute("result");
}
public JSONObject lastSub(String username) throws ClientProtocolException, IOException, JSONException {
StringBuilder url = new StringBuilder(URL);
url.append(username);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if(status == 200) {
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONObject last = new JSONObject(data);
//JSONObject last = new JSONObject(data).getJSONArray("result").getJSONObject(0).getJSONObject("problem");
JSONArray array = new JSONObject(data).getJSONArray("result");
String m1=null, m2=null, m3=null;
String n1 = System.getProperty("line.separator");
int cnt=0, flag=0;
for(int k=0; k<array.length(); k++)
{
last = array.getJSONObject(k).getJSONObject("problem");
JSONObject v = array.getJSONObject(k);
if(v.getString("verdict").contentEquals("OK")) {
m1 = last.getString("name");
m2= last.getString("contestId");
m2= m2.concat("/");
m3= last.getString("index");
m2 = m2.concat(m3);
flag = 0;
for(int i=0; i<cnt; i++) {
if (sarr[i].equals(m1)) {
flag = 1;
}
}
if(flag == 0) {
m = m.concat(m1);
m= m.concat(n1);
sarr[cnt] = m1;
name[cnt] = m2;
cnt++;
}
}
}
return last;
}
else {
Toast.makeText(Http.this, "error", Toast.LENGTH_SHORT);
return null;
}
}
public class Read extends AsyncTask <String, Integer, String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
json = lastSub("avm12&from=1&count=100");
return m;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
httpStuff.setText(result);
}
}
}
Make sure your main layout R.layout.httpex has a ListView.
(Should look like this)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Create a new layout list_item.xml representing the data you want to display :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/pTitle"
android:textAppearance="#android:style/TextAppearance.DeviceDefault.Medium"
android:padding="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/pUrl"
android:visibility="gone" />
</LinearLayout>
Then edit your code like this :
public class Http extends Activity {
TextView httpStuff;
HttpClient client;
JSONObject json;
final static String URL = "http://codeforces.com/api/user.status?handle=";
String m = "";
ListView list;
public static ArrayList<HashMap<String, String>> problemdata= new ArrayList<HashMap<String, String>>();
//above ArrayList replacing sarr & name
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.httpex);
list=(ListView)findViewById(R.id.list);
httpStuff = (TextView)findViewById(R.id.tvHttp);
client = new DefaultHttpClient();
new Read().execute("result");
}
public JSONObject lastSub(String username) throws ClientProtocolException, IOException, JSONException {
StringBuilder url = new StringBuilder(URL);
url.append(username);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONObject last = new JSONObject(data);
//JSONObject last = new JSONObject(data).getJSONArray("result").getJSONObject(0).getJSONObject("problem");
JSONArray array = new JSONObject(data).getJSONArray("result");
String n1 = System.getProperty("line.separator");
for (int k = 0; k < array.length(); k++) {
last = array.getJSONObject(k).getJSONObject("problem");
JSONObject v = array.getJSONObject(k);
if (v.getString("verdict").contentEquals("OK")) {
HashMap<String, String> d = new HashMap<String, String>();
d.put("NAME",last.getString("name"));
d.put("URL","http://codeforces.com/problemset/problem/"+last.getString("contestId")+"/"+last.getString("index"));
if(!problemdata.contains(d)) {
m = m.concat(last.getString("name")).concat(n1); //m+=last.getString("name")+"\r\n";
problemdata.add(d);
}
}
}
return last;
} else {
Toast.makeText(Http.this, "error", Toast.LENGTH_SHORT);
return null;
}
}
public class Read extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
json = lastSub("avm12&from=1&count=100");
return m;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
httpStuff.setText(result);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//get the url from the invisible TextView ad opens it on the default browser
TextView t=(TextView)view.findViewById(R.id.pUrl);
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(t.getText().toString())));
}
});
ListAdapter adapter = new SimpleAdapter(
Http.this, problemdata,
R.layout.list_item, new String[] { "NAME", "URL" }, new int[] { R.id.pTitle,
R.id.pUrl});
list.setAdapter(adapter);
}
}
}

Android currency converter application

I'm working on a big program for Android and I'm trying to get the currency converter part of the program to work. For full disclosure: I found it from http://firstamong.com/building-android-currency-converter/, and it's a tutorial on how to build a real-time currency converter. I'll post the code in question followed by the logcat. The error that occurs is when I try to convert from one currency to another, the application says it was forced to stop. However, the "Invalid" portion works (the case where both currency fields are the same.) Any help would truly be appreciated:
Code:
public class currency_converter extends Activity {
public int to;
public int from;
public String [] val;
public String s;
public Handler handler;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_currency_converter);
Spinner s1 = (Spinner) findViewById(R.id.spinner1);
Spinner s2 = (Spinner) findViewById(R.id.spinner2);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.name, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
val = getResources().getStringArray(R.array.value);
s1.setAdapter(adapter);
s2.setAdapter(adapter);
s1.setOnItemSelectedListener(new spinOne(1));
s2.setOnItemSelectedListener(new spinOne(2));
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
TextView t = (TextView) findViewById(R.id.textView4);
if(from == to)
{
Toast.makeText(getApplicationContext(), "Invalid", 4000).show();
}
else
{
try {
s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"+val[from]+val[to]+"%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
JSONObject jObj;
jObj = new JSONObject(s);
String exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
t.setText(exResult);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
}
public String getJson(String url)throws ClientProtocolException, IOException {
StringBuilder build = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String con;
while ((con = reader.readLine()) != null) {
build.append(con);
}
return build.toString();
}
private class spinOne implements OnItemSelectedListener
{
int ide;
spinOne(int i)
{
ide =i;
}
public void onItemSelected(AdapterView<?> parent, View view,
int index, long id) {
if(ide == 1)
from = index;
else if(ide == 2)
to = index;
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
class GetResponseData extends AsyncTask<String, String, String> {
private ProgressDialog dialog;
private ArrayList<String> titleList;
private TextView textView;
public GetResponseData(TextView textView) {
this.textView = textView;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = ProgressDialog.show(currency_converter.this, "", "Loading",
false);
}
#Override
protected String doInBackground(String... params) {
try {
String s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22" + val[from] + val[to] + "%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
JSONObject jObj;
jObj = new JSONObject(s);
String exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
return exResult;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (dialog != null)
dialog.dismiss();
if (result != null) {
textView.setText(result);
}
}
}
}
}
Logcat:
10-30 00:59:48.164 20591-20591/com.example.travelapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1128)
at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:365)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:587)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:511)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:489)
at com.example.travelapplication.currency_converter.getJson(currency_converter.java:93)
at com.example.travelapplication.currency_converter$1.onClick(currency_converter.java:68)
at android.view.View.performClick(View.java:4222)
at android.view.View$PerformClick.run(View.java:17620)
at android.os.Handler.handleCallback(Handler.java:800)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5391)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Try this,,
Your performing a networking operation on its main thread. That why your getting NetworkOnMainThreadException
b.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
TextView t = (TextView) findViewById(R.id.textView4);
if(from == to)
{
Toast.makeText(getApplicationContext(), "Invalid", 4000).show();
}
else
{
GetResponseData abcd = GetResponseData(t);
abcd.execute();
}
}
});
You are getting:
NetworkOnMainThreadException
Issue is that you are calling your function getJson() in your Activity.
Use AsyncTask:
public class ProcessTask extends AsyncTask<Void, Integer, String>{
public ProcessTask() {
// TODO Auto-generated constructor stub
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
//your code of parsing
StringBuilder build = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url); //your yahooapi url goes here
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String con;
while ((con = reader.readLine()) != null) {
build.append(con);
}
return build.toString();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
It looks like you have strict mode on in your android manifest. Strict mode will complain when you are doing network calls on you main thread. You can just disable strict mode or a better approach is to put your network call into an async task. The network call in question is
HttpResponse response = client.execute(httpGet);
inside public String getJson(String url)
The async task you need is already there you just need to use it
Change this else statement
else
{
try {
s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"+val[from]+val[to]+"%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
JSONObject jObj;
jObj = new JSONObject(s);
String exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
t.setText(exResult);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
To this
else {
new GetResponseData().execute("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"+val[from]+val[to]+"%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
}
It will help use this :
public class CurrencyConverter extends Fragment {
public CurrencyConverter() {
}
TextView t;
public int to;
public int from;
public String[] val;
public String s;
String exResult;
public Handler handler;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.currency_converter, container, false);
t= (TextView) rootView.findViewById(R.id.textView4);
Spinner s1 = (Spinner) rootView.findViewById(R.id.spinner1);
Spinner s2 = (Spinner) rootView.findViewById(R.id.spinner2);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this.getActivity(), R.array.name, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
val = getResources().getStringArray(R.array.value);
s1.setAdapter(adapter);
s2.setAdapter(adapter);
s1.setOnItemSelectedListener(new spinOne(1));
s2.setOnItemSelectedListener(new spinOne(2));
Button b = (Button) rootView.findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View View) {
if (from == to) {
Toast.makeText(getActivity().getApplicationContext(), "Invalid", 4000).show();
} else {
new calculate().execute();
}
}
});
return rootView;
}
public class calculate extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... args) {
try {
s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"+val[from]+val[to]+"%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
JSONObject jObj;
jObj = new JSONObject(s);
exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return exResult;
}
#Override
protected void onPostExecute(String exResult) {
t.setText(exResult);
}
}
public String getJson(String url)throws IOException {
StringBuilder build = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String con;
while ((con = reader.readLine()) != null) {
build.append(con);
}
return build.toString();
}
public class spinOne implements AdapterView.OnItemSelectedListener
{
int ide;
spinOne(int i)
{
ide =i;
}
public void onItemSelected(AdapterView<?> parent, View view,
int index, long id) {
if(ide == 1)
from = index;
else if(ide == 2)
to = index;
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
}

my llistview load multiple time same data on screen

my listview repeat data some time which click on buttons fastly what do i do please help me see this images http://imgur.com/ed5uDtp after some time is show like this http://imgur.com/jAt4yn7
is show correctly data on listview but some time when click fastly buttons is load duplicate data how i will fixed this? plaa help me
public class thirdstep extends Activity implements View.OnClickListener {
int count = 0;
String id;
String title;
String tmpString, finaldate;
String valll;
ProgressBar prgLoading;
TextView txtAlert;
int IOConnect = 0;
String mVal9;
Button e01;
Button e02;
Button e03;
Button e04;
Button e05;
String SelectMenuAPI;
String url;
String URL;
String URL2, URL3, URL4;
String menu_title;
JSONArray school;
ListView listCategory;
String status;
String School_ID;
String Menu_ID;
String School_name;
String Meal_groupid;
String _response;
String _response2;
String CategoryAPI;
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>();
String mydate;
String mode;
String s2;
ArrayList<String> myList,myList2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_list2);
listCategory = (ListView) findViewById(R.id.thirdscreenlist);
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
txtAlert = (TextView) findViewById(R.id.txtAlert);
e01 = (Button) findViewById(R.id.e01);
e02 = (Button) findViewById(R.id.e02);
e03 = (Button) findViewById(R.id.e03);
e04 = (Button) findViewById(R.id.e04);
e05 = (Button) findViewById(R.id.e05);
e01.setOnClickListener(this);
e02.setOnClickListener(this);
e03.setOnClickListener(this);
e04.setOnClickListener(this);
e05.setOnClickListener(this);
cla = new thirdstepAdapter(thirdstep.this);
listCategory.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Intent intent = new Intent(thirdstep.this, fifthscreen.class);
startActivity(intent);
}
});
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() {
if (!prgLoading.isShown()) {
prgLoading.setVisibility(0);
txtAlert.setVisibility(8);
}
}
#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
prgLoading.setVisibility(8);
if ((Category_ID.size() > 0) || IOConnect == 0) {
listCategory.setAdapter(cla);
cla.notifyDataSetChanged() ;
listCategory.invalidateViews();
} else {
txtAlert.setVisibility(0);
menu_nametxt.setText("");
listCategory.setVisibility(View.GONE);
}
}
}
public void parseJSONData() {
clearData();
SelectMenuAPI="";
SelectMenuAPI = Utils.Schoolmenu +Menu_ID+"&sid="+School_ID+"&lid=" +
SchoolLevelId+"&mealid="+Meal_groupid;
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 json5 = new JSONObject(_response);
status = json5.getString("status");
if (status.equals("1")) {
JSONArray school5 = json5.getJSONArray("data");
}
}
else {
}
SelectMenuAPI2="";
SelectMenuAPI2 = Utils.SchoolVacation+mVal9;
// clearData();
URL3 = SelectMenuAPI2;
URL4 = URL3.replace(" ", "%20");
Log.i("url",""+URL4);
JSONObject json2 = new JSONObject(_response);
status = json2.getString("status");
if (status.equals("1")) {
if (Vacation_Date.contains(mydate)) {
message = "holiday";
JSONObject json4 = new JSONObject(str2);
status = json4.getString("status");
if (status.equals("1")) {
school = json4.getJSONArray("data");
for (int k = 0; k < school.length(); k++) {
JSONObject jb = (JSONObject) school .getJSONObject(k);
Vacation_ID.add((long) k);
String[] mVal = new String[school.length()];
if(school.getJSONObject(k).getString("date").equals(mydate))
{
mVal[k] = school.getJSONObject(k).getString("title");
mVal3 = mVal[k];
}
}
}
} else {
JSONArray school = json2.getJSONArray("data");
for (int i = 0; i < school.length(); i++) {
JSONObject object = school.getJSONObject(i);
if (object.getString("Schedule").equals("weekly")) {
if (object.getString("day").equals(Todayday)) {
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];
}
}
if(dish_name != null &&
!dish_name.isEmpty())
{
message = "weekly";
}
else {
message = "error";
}
}
else {
message = "error";
}
}
}
}
else {
message = "error";
}
} 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();
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.e01:
// do stuff;
listCategory.setVisibility(View.GONE);
new getDataTask().execute();
break;
case R.id.e02:
// do stuff;
listCategory.setVisibility(View.GONE);
new getDataTask().execute();
break;
case R.id.e03:
// do stuff;
listCategory.setVisibility(View.GONE);
new getDataTask().execute();
break;
case R.id.e04:
// do stuff;
listCategory.setVisibility(View.GONE);
new getDataTask().execute();
break;
case R.id.e05:
listCategory.setVisibility(View.GONE);
// do stuff;
new getDataTask().execute();
break;
}
}
}
You are calling asynctask twice and that is making all parts twice, I mean you are cleaning twice before filling and fill arrays twice. You should control your async task for do not execute before last one finished.
1-Create a boolean value
2-Put condition on onClicks:
if(yourBoolean){
new getDataTask().execute();}
3- in your asyncTask's onPreExecute make yourBoolean=false and onPostExecute make yourBoolean=true again.
Try this..
Just remove the below line and try it..
listCategory.invalidateViews();
because
ListView.invalidateViews() is used to tell the ListView to invalidate all its child item views (redraw them). Note that there not need to be an equal number of views than items. That's because a ListView recycles its item views and moves them around the screen in a smart way while you scroll.

how to update Ui from background task

My app is not working on android version 4.1 gives exception like android.os.NetworkOnMainThreadException
i have search on stackoverflow advice me to do network thread in background AsyncTask so before use backgroundtask,
My screen look like this http://imgur.com/PlhS03i show multiple rows in nutrition's and ingredient tags after using backgroundtask my screen look like this http://imgur.com/zUvxNpy show only single row in ingredients and nutrition tags
before background task code is this see below
public class fifthscreen extends Activity {
String num = null;
TextView ingredient;
long Menu_ID;
String dish_name;
String status;
HorizontalListView listview;
CategoryListAdapter3 cla;
String DescriptionAPI;
TextView txt1, txt2, txt3;
ImageView img1;
String URL, URL2;
String SelectMenuAPI;
static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
public static String allergen2;
private AQuery androidAQuery;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fifthscreen);
ingredient = (TextView) findViewById(R.id.ingredient);
img1 = (ImageView) findViewById(R.id.test_button_image);
txt1 = (TextView) findViewById(R.id.menuname);
txt3 = (TextView) findViewById(R.id.description);
Intent iGet = getIntent();
ImageView options = (ImageView) findViewById(R.id.options5);
androidAQuery = new AQuery(this);
options.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent iMenuList = new Intent(fifthscreen.this,
LinkButtons.class);
startActivity(iMenuList);
}
});
dish_name = iGet.getStringExtra("dish_name");
listview = (HorizontalListView) this.findViewById(R.id.listview2);
cla = new CategoryListAdapter3(fifthscreen.this);
listview.setAdapter(cla);
parseJSONData();
}
void clearData() {
Category_ID.clear();
Category_name.clear();
Category_image.clear();
}
public void parseJSONData() {
SelectMenuAPI = Utils.dishdescription + dish_name;
clearData();
URL = SelectMenuAPI;
URL2 = URL.replace(" ", "%20");
try {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams
.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(URL2);
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;
}
JSONObject json2 = new JSONObject(str);
status = json2.getString("status");
if (status.equals("1")) {
JSONArray school2 = json2.getJSONArray("data");
for (int i = 0; i < school2.length(); i++) {
String name = school2.getJSONObject(0).getString("name");
txt1.setText(name);
String description = school2.getJSONObject(0).getString(
"description");
txt3.setText(description);
String url1 = school2.getJSONObject(0).getString("image");
androidAQuery.id(img1).image(url1, false, false);
}
JSONObject school3 = json2.getJSONObject("dish_nutrition");
final TableLayout table = (TableLayout) findViewById(R.id.table2);
for (int j = 0; j < school3.length(); j++) {
String s = String.valueOf(j + 1);
final View row = createRow(school3.getJSONObject(s));
table.addView(row);
}
JSONArray school4 = json2.getJSONArray("dish_allergen");
//
for (int i = 0; i < school4.length(); i++) {
JSONObject object = school4.getJSONObject(i);
Category_ID.add((long) i);
Category_name.add(object.getString("name"));
Category_image.add(object.getString("image"));
listview.setAdapter(cla);
}
final LinearLayout table3 = (LinearLayout) findViewById(R.id.table3);
JSONArray school5 = json2.getJSONArray("dish_ingredient");
for (int i = 0; i < school5.length(); i++) {
final View row2 = createRow2(school5.getJSONObject(i));
table3.addView(row2);
}
}
else {
JSONArray school2 = json2.getJSONArray("data");
for (int i = 0; i < school2.length(); i++) {
JSONObject object = school2.getJSONObject(i);
Category_ID.add((long) i);
Category_name.add(object.getString("name"));
}
}
} 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();
}
}
public View createRow(JSONObject item) throws JSONException {
View row = getLayoutInflater().inflate(R.layout.rows, null);
((TextView) row.findViewById(R.id.localTime)).setText(item
.getString("qty"));
((TextView) row.findViewById(R.id.apprentTemp)).setText(item
.getString("name"));
return row;
}
public View createRow2(JSONObject item) throws JSONException {
View row2 = getLayoutInflater().inflate(R.layout.row2, null);
((TextView) row2.findViewById(R.id.name)).setText(item
.getString("name"));
((TextView) row2.findViewById(R.id.subingredients)).setText(item
.getString("sub_ingredients"));
return row2;
}
}
After using AsyncTask see this code below
public class fifthscreen extends Activity {
String num = null;
TextView ingredient;
long Menu_ID;
String dish_name;
String status;
HorizontalListView listview;
CategoryListAdapter3 cla;
String DescriptionAPI;
TextView txt1, txt2, txt3;
ImageView img1;
String URL, URL2;
String SelectMenuAPI;
String description;
int IOConnect = 0;
String name;
String url1;
TableLayout table;
LinearLayout table3;
View row;
View row2;
static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
public static String allergen2;
private AQuery androidAQuery;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fifthscreen);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
ingredient = (TextView) findViewById(R.id.ingredient);
img1 = (ImageView) findViewById(R.id.test_button_image);
txt1 = (TextView) findViewById(R.id.menuname);
// txt2 = (TextView) findViewById(R.id.test_button_text1);
txt3 = (TextView) findViewById(R.id.description);
table = (TableLayout) findViewById(R.id.table2);
table3 = (LinearLayout) findViewById(R.id.table3);
Intent iGet = getIntent();
ImageView options = (ImageView) findViewById(R.id.options5);
androidAQuery = new AQuery(this);
options.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent iMenuList = new Intent(fifthscreen.this,
LinkButtons.class);
startActivity(iMenuList);
}
});
dish_name = iGet.getStringExtra("dish_name");
listview = (HorizontalListView) this.findViewById(R.id.listview2);
cla = new CategoryListAdapter3(fifthscreen.this);
new getDataTask().execute();
// listview.setAdapter(cla);
ImageView btnback = (ImageView) findViewById(R.id.btnback);
btnback.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
parseJSONData();
}
void clearData() {
Category_ID.clear();
Category_name.clear();
Category_image.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
txt1.setText(name);
txt3.setText(description);
androidAQuery.id(img1).image(url1, false, false);
table.addView(row);
table3.addView(row2);
listview.setAdapter(cla);
}
}
public void parseJSONData() {
SelectMenuAPI = Utils.dishdescription + dish_name;
clearData();
URL = SelectMenuAPI;
URL2 = URL.replace(" ", "%20");
try {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams
.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(URL2);
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;
}
JSONObject json2 = new JSONObject(str);
status = json2.getString("status");
if (status.equals("1")) {
JSONArray school2 = json2.getJSONArray("data");
for (int i = 0; i < school2.length(); i++) {
name = school2.getJSONObject(0).getString("name");
description = school2.getJSONObject(0).getString(
"description");
url1 = school2.getJSONObject(0).getString("image");
}
JSONObject school3 = json2.getJSONObject("dish_nutrition");
for (int j = 0; j < school3.length(); j++) {
String s = String.valueOf(j + 1);
row = createRow(school3.getJSONObject(s));
}
JSONArray school4 = json2.getJSONArray("dish_allergen");
//
for (int i = 0; i < school4.length(); i++) {
JSONObject object = school4.getJSONObject(i);
Category_ID.add((long) i);
Category_name.add(object.getString("name"));
Category_image.add(object.getString("image"));
}
JSONArray school5 = json2.getJSONArray("dish_ingredient");
for (int i = 0; i < school5.length(); i++) {
row2 = createRow2(school5.getJSONObject(i));
}
}
else {
JSONArray school2 = json2.getJSONArray("data");
for (int i = 0; i < school2.length(); i++) {
JSONObject object = school2.getJSONObject(i);
Category_ID.add((long) i);
Category_name.add(object.getString("name"));
}
}
} 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();
}
}
public View createRow(JSONObject item) throws JSONException {
View row = getLayoutInflater().inflate(R.layout.rows, null);
((TextView) row.findViewById(R.id.localTime)).setText(item
.getString("qty"));
((TextView) row.findViewById(R.id.apprentTemp)).setText(item
.getString("name"));
return row;
}
public View createRow2(JSONObject item) throws JSONException {
View row2 = getLayoutInflater().inflate(R.layout.row2, null);
((TextView) row2.findViewById(R.id.name)).setText(item
.getString("name"));
((TextView) row2.findViewById(R.id.subingredients)).setText(item
.getString("sub_ingredients"));
return row2;
}
}
Please Help
Thanks in Advance...:)
Use the Handler object from your MainActivity and post a runnable. To use it from the backgrund you need to make the object a static that you can call outside of your MainActivity or you can create a static instance of the Activity to access it.
Inside the Activity
private static Handler handler;
handler = new Handler();
handler().post(new Runnable() {
public void run() {
//ui stuff here :)
}
});
public static Handler getHandler() {
return handler;
}
Outside the Activity
MainActivity.getHandler().post(new Runnable() {
public void run() {
//ui stuff here :)
}
});
You can use **runOnUiThread()** like this:
try {
// code runs in a thread
runOnUiThread(new Runnable() {
#Override
public void run() {
// YOUR CODE
}
});
} catch (final Exception ex) {
Log.i("---","Exception in thread");
}
You need to create AsyncTask class and use it
Read here more: AsyncTask
Example would look like this:
private class UploadTask extends AsyncTask<Void, Void, Void>
{
private String in;
public UploadTask(String input)
{
this.in = input;
}
#Override
protected void onPreExecute()
{
//start showing progress here
}
#Override
protected Void doInBackground(Void... params)
{
//do your work
return null;
}
#Override
protected void onPostExecute(Void result)
{
//stop showing progress here
}
}
And start task like this:
UploadTask ut= new UploadTask(input);
ut.execute();
you are handling ui in these methods
public View createRow(JSONObject item) throws JSONException {
View row = getLayoutInflater().inflate(R.layout.rows, null);
((TextView) row.findViewById(R.id.localTime)).setText(item
.getString("qty"));
((TextView) row.findViewById(R.id.apprentTemp)).setText(item
.getString("name"));
return row;
}
public View createRow2(JSONObject item) throws JSONException {
View row2 = getLayoutInflater().inflate(R.layout.row2, null);
((TextView) row2.findViewById(R.id.name)).setText(item
.getString("name"));
((TextView) row2.findViewById(R.id.subingredients)).setText(item
.getString("sub_ingredients"));
return row2;
}
which are called in background thread
if possible do it in onPostExecute or you can use runOnUiThread and Handler.

Categories

Resources