我确实通过http读取数据,但我无法将此数据分配给TextView。
当我在xml文件中创建TextView时,数据被分配到normal。但是当我以编程方式创建TextView时,文本为空。
public class News extends Activity
{
TextView myText;
TextView title1;
String s = "";
@SuppressLint({ "NewApi", "ResourceAsColor" }) @Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.news);
StrictMode.enableDefaults();
int textId1 = 1;
int textId2 = 2;
title1 = new TextView(this);
title1.setText("Заголовок новости 1 - 2013.01.01\n\nСегодня состоится заседание зампредпал тра та та");
title1.setTextColor(getResources().getColor(R.color.colorWihte));
title1.setShadowLayer(2, 0, 0,getResources().getColor(R.color.colorBlack));
title1.setBackground(getResources().getDrawable(R.drawable.round_block));
title1.setId(textId1);
RelativeLayout.LayoutParams layoutParams1 = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutParams1.addRule(RelativeLayout.ALIGN_PARENT_TOP);
layoutParams1.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
layoutParams1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
title1.setLayoutParams(layoutParams1);
((ViewGroup) findViewById(R.id.newslayout)).addView(title1);
String result = "";
InputStream isr = null;
try
{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://test.ivanov-vladimir.com/get_content.php");
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
}
catch(Exception e)
{
Log.e("log_tag", "HTTP connect error " + e.toString());
}
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr, "utf-8"), 8);
StringBuilder builder = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
builder.append(line + "\n");
}
isr.close();
result = builder.toString();
}
catch(Exception e)
{
Log.e("log_tag", "Data converting error " + e.toString());
}
try
{
JSONArray jarray = new JSONArray(result);
for(int i = 0; i < jarray.length(); i++)
{
JSONObject json = jarray.getJSONObject(i);
s = "Title: " + json.getString("title") + "\n\nContent: " + json.getString("content");
}
}
catch(Exception e)
{
Log.e("log_tag", "Data parsing error " + e.toString());
}
title1.setText(s);
}
}
现在我正在尝试为元素title1分配数组 jarray的最后一个值。
我在YouTube上的视频教程中获得了此代码。
如果你去一个网址http://test.ivanov-vladimir.com/get_content.php会打印符号,因为数据库中的文字是西里尔文。
答案 0 :(得分:0)
首先,尝试避免UI线程中的网络操作等长时间操作,这会降低您的应用程序速度。
然后,尝试获取TextView值并记录它以查看是否为TextView分配了值:
Log.v("TextView value", title1.getText().toString());
然后,您还可以尝试从Web服务中记录内容下载:
while((line = reader.readLine()) != null)
{
builder.append(line + "\n");
Log.v("line", line);
}
请提供日志结果。